Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
848 views
in Technique[技术] by (71.8m points)

json - Java - Gson parsing nested within nested

I have to interact with an API, and the response format (from what I've read) seems to be poorly structured. I've found a google groups reply to a somewhat similiar problem here, but I'm having trouble implementing a Response class to handle the Gson.fromJson. Is there an example I'm missing that's out there?

{

"response":{
    "reference": 1023, 
    "data":{
        "user":{
            "id":"210",
            "firstName":"john",
            "lastName":"smith",
            "email":"[email protected]",
            "phone":"",
            "linkedid":{
                "id":"238"
            }
        }
    }
}

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JSON objects {} can be represented by a Map<String, Object> or a Javabean class. Here's an example which uses a Javabean.

public class ResponseData {
    private Response response;
    // +getter+setter

    public static class Response {
        private int reference;
        private Data data;
        // +getters+setters
    }

    public static class Data {
        private User user;
        // +getter+setter
    }

    public static class User {
        private String id;
        private String firstName; 
        private String lastName;
        private String email;
        private String phone;
        private Linkedid linkedid;
        // +getters+setters
    }

    public static class Linkedid {
        private String id;
        // +getter+setter
    }
}

Use it as follows:

ResponseData responseData = new Gson().fromJson(json, ResponseData.class);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...