简体   繁体   中英

json Array to bean ( object mapper )

Read the json object and store into the bean by creating the new getter n setter. I want to read the bold value from below json object received as string.

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

Bean:

@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();
        }

I am successfully able to read the country but I want to read other values which are in bold above

CoronaBean should contain property provinces , which must be another Bean with properties you want from there. Simple as that.

Look at the code:

@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

I think you can also check this question for more details and ways to achive what you need: How to parse JSON in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM