简体   繁体   中英

Parsing JSON response using GSON or java alternatives

I have this JSON response from graph API to friend mutual friends

 {"context":{"mutual_friends":{"data":[{"name":"T Ate Hondrad","id":"10206554047069160"},{"name":"Pushkar Verma","id":"10203898838385903"}],"paging":{"cursors":{"before":"MTAyMDY1NTQwNDcwNjkxNjAZD","after":"MTAyMDM4OTg4MzgzODU5MDMZD"}},"summary":{"total_count":2}},"id":"dXNlcl9jb250ZAXh0OgGQEqErvwsZCMyDY9RoYFTqaRBTPrIksArHbUAn6t92n2ttzeW8av8W1ZBZAZAZCz4g7yNZCAo8db4WHArx6irNdS9eM6wB6TjQGhZC7ZCnDezjI2PjaU4ZD"},"id":"164585393877089"}

I am using this approach

JSONObject json = new JSONObject(jsonText);
    if (json.has("context")) {
        JSONObject context = json.getJSONObject("context");
        if (context.has("mutual_friends")) {            
            JSONObject mutual_friends = new JSONObject("mutual_friends");
            if (mutual_friends.has("data")) {
                JSONArray data = mutual_friends.getJSONArray("data");
            }
        }
    }

Using Gson

com.app.model.Context ctx = new Gson().fromJson(jsonText, com.app.model.Context.class);

The problem is either way I am unable to read data array of JSONObjects

jsonText is a String variable with json

Context Class

public class Context
{
private String id;

private Mutual_friends mutual_friends;

public String getId ()
{
    return id;
}

public void setId (String id)
{
    this.id = id;
}

public Mutual_friends getMutual_friends ()
{
    return mutual_friends;
}

public void setMutual_friends (Mutual_friends mutual_friends)
{
    this.mutual_friends = mutual_friends;
}

@Override
public String toString()
{
    return "ClassPojo [id = "+id+", mutual_friends = "+mutual_friends+"]";
}
}

Mutual_friends Class

public class Mutual_friends {


private Data[] data;


public Data[] getData() {
    return data;
}

public void setData(Data[] data) {
    this.data = data;
}


@Override
public String toString() {
    return "ClassMutualFrinds [ data = " + data + "]";
}
}

Data Class

public class Data
 {
private String id;

private String name;

public String getId ()
{
    return id;
}

public void setId (String id)
{
    this.id = id;
}

public String getName ()
{
    return name;
}

public void setName (String name)
{
    this.name = name;
}

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Data data = (Data) o;

    return !(id != null ? !id.equals(data.id) : data.id != null);

}

@Override
public int hashCode() {
    return id != null ? id.hashCode() : 0;
}

@Override
public String toString()
{
    return "ClassPojo [id = "+id+", name = "+name+"]";
}
}

According to your JSON Response.

Below should be the JAVA Files should be :

Context.JAVA

public class Context {

@SerializedName("mutual_friends")
@Expose
private MutualFriends mutualFriends;
@SerializedName("id")
@Expose
private String id;

/**
* 
* @return
* The mutualFriends
*/
public MutualFriends getMutualFriends() {
return mutualFriends;
}

/**
* 
* @param mutualFriends
* The mutual_friends
*/
public void setMutualFriends(MutualFriends mutualFriends) {
this.mutualFriends = mutualFriends;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

}

Cursors.java

public class Cursors {

@SerializedName("before")
@Expose
private String before;
@SerializedName("after")
@Expose
private String after;

/**
* 
* @return
* The before
*/
public String getBefore() {
return before;
}

/**
* 
* @param before
* The before
*/
public void setBefore(String before) {
this.before = before;
}

/**
* 
* @return
* The after
*/
public String getAfter() {
return after;
}

/**
* 
* @param after
* The after
*/
public void setAfter(String after) {
this.after = after;
}

}

Datum.JAVA

public class Datum {

@SerializedName("name")
@Expose
private String name;
@SerializedName("id")
@Expose
private String id;

/**
* 
* @return
* The name
*/
public String getName() {
return name;
}

/**
* 
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

}

Example.java

public class Example {

@SerializedName("context")
@Expose
private Context context;
@SerializedName("id")
@Expose
private String id;

/**
* 
* @return
* The context
*/
public Context getContext() {
return context;
}

/**
* 
* @param context
* The context
*/
public void setContext(Context context) {
this.context = context;
}

/**
* 
* @return
* The id
*/
public String getId() {
return id;
}

/**
* 
* @param id
* The id
*/
public void setId(String id) {
this.id = id;
}

}

MutualFriends.java

public class MutualFriends {

@SerializedName("data")
@Expose
private List<Datum> data = new ArrayList<Datum>();
@SerializedName("paging")
@Expose
private Paging paging;
@SerializedName("summary")
@Expose
private Summary summary;

/**
* 
* @return
* The data
*/
public List<Datum> getData() {
return data;
}

/**
* 
* @param data
* The data
*/
public void setData(List<Datum> data) {
this.data = data;
}

/**
* 
* @return
* The paging
*/
public Paging getPaging() {
return paging;
}

/**
* 
* @param paging
* The paging
*/
public void setPaging(Paging paging) {
this.paging = paging;
}

/**
* 
* @return
* The summary
*/
public Summary getSummary() {
return summary;
}

/**
* 
* @param summary
* The summary
*/
public void setSummary(Summary summary) {
this.summary = summary;
}

}

Paging.java

public class Paging {

@SerializedName("cursors")
@Expose
private Cursors cursors;

/**
* 
* @return
* The cursors
*/
public Cursors getCursors() {
return cursors;
}

/**
* 
* @param cursors
* The cursors
*/
public void setCursors(Cursors cursors) {
this.cursors = cursors;
}

}

Summary.java

public class Summary {

@SerializedName("total_count")
@Expose
private Integer totalCount;

/**
* 
* @return
* The totalCount
*/
public Integer getTotalCount() {
return totalCount;
}

/**
* 
* @param totalCount
* The total_count
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}

}

Finally, what you will need to get instance of Context is below lines :

      Context ctx = new Gson().fromJson(jsonText, Context.class);

Please make sure you are importing correct Context class.

After reading Bhavesh's answer as I have asked him about generator of these POJO classes

I searched around and found www.jsonschema2pojo.org

Selected Source as JSON and Annotation style: as Gson and other options and generator the Classes

What I did extra is I unCheked allow extra properties and generated POJO classes were able to parse given json using GSON

Context ctx = new Gson().fromJson(jsonText, Context.class);

My POJO is below

        -----------------------------------com.app.Context.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Context {

        @SerializedName("context")
        @Expose
        public Context_ context;
        @SerializedName("id")
        @Expose
        public String id;

    }
    -----------------------------------com.app.Context_.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Context_ {

        @SerializedName("mutual_friends")
        @Expose
        public MutualFriends mutualFriends;
        @SerializedName("id")
        @Expose
        public String id;

    }
    -----------------------------------com.app.Cursors.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Cursors {

        @SerializedName("before")
        @Expose
        public String before;
        @SerializedName("after")
        @Expose
        public String after;

    }
    -----------------------------------com.app.Datum.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Datum {

        @SerializedName("name")
        @Expose
        public String name;
        @SerializedName("id")
        @Expose
        public String id;

    }
    -----------------------------------com.app.MutualFriends.java-----------------------------------

    package com.app;

    import java.util.ArrayList;
    import java.util.List;
    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class MutualFriends {

        @SerializedName("data")
        @Expose
        public List<Datum> data = new ArrayList<Datum>();
        @SerializedName("paging")
        @Expose
        public Paging paging;
        @SerializedName("summary")
        @Expose
        public Summary summary;

    }
    -----------------------------------com.app.Paging.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Paging {

        @SerializedName("cursors")
        @Expose
        public Cursors cursors;

    }
    -----------------------------------com.app.Summary.java-----------------------------------

    package com.app;

    import javax.annotation.Generated;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;

    @Generated("org.jsonschema2pojo")
    public class Summary {

        @SerializedName("total_count")
        @Expose
        public Integer totalCount;

    }

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