json数组到bean(对象Map器)

kyxcudwk  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(450)

读取json对象并通过创建新的getternsetter将其存储到bean中。我想从下面的json对象中读取作为字符串接收的粗体值。

[{"country":"**India**","provinces":[{**"province":"India","confirmed":265928,"recovered":129095,"deaths":7473,"active":129360**}],"latitude":20.593684,"longitude":78.96288,"date":"2020-06-08"}]

豆子:

@JsonIgnoreProperties(ignoreUnknown = true)
public class CoronaBean {
private String country; } and other needs to be created
ObjectMapper mapper = new ObjectMapper();
        try {
            CoronaBean[] coronaBean = mapper.readValue(json, CoronaBean[].class);
            for(CoronaBean c: coronaBean ){
            System.out.println(c.getCountry());
            }
        } catch (JsonProcessingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我能成功地读懂这个国家,但我想读懂上面加粗的其他价值观

dnph8jn4

dnph8jn41#

CoronaBean 应包含属性 provinces ,它必须是另一个bean,其中包含您想要的属性。就这么简单。
看看代码:

@JsonIgnoreProperties(ignoreUnknown = true)
public class CoronaBean {
private String country; 
private ProvinceBean[] provinces
...getters and setters

} 

@JsonIgnoreProperties(ignoreUnknown = true)
public class ProvinceBean {
private Integer confirmed;
private Integer recovered;
...rest you want and getters and setters

我认为您还可以检查这个问题,了解更多细节和实现所需的方法:如何在java中解析json

相关问题