简体   繁体   中英

Parse json with Objects to model Object - Java Spring

I have model:

public class StudyModel {
    @Id
    private String ID;
    private boolean isStable;
    private String LastUpdate;
    private MainTest test;

    public static class MainTest {
        private String test1;
        private String test2;
    }
}

I want to parse it to my model.
It works correctly but when it goes to MainTest where on json file I have couple values it fails and I have null on the rest of fields.
How I can deal with it?

public StudyModel getStudyDetails(String studyId){
        RestTemplate restTemplate = new RestTemplate();
        String url = URL + "studies/" + studyId;
        ResponseEntity<String> serverResponse = restTemplate.getForEntity(url, String.class);
        Gson g = new Gson();
        String json = serverResponse.getBody();
        StudyModel study = g.fromJson(json, StudyModel.class);

        return study;
}

RestTemplate can handle deserialization for you

ResponseEntity<StudyModel> serverResponse = restTemplate.getForEntity(url, StudyModel.class);
StudyModel studyModel = serverResponse.getBody();

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