Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSon Data using java (google-gson)

Tags:

java

json

gson

Trying to learn how to use JSON and parse the json data.i am using google-gson API to parse my json data.

i am getting my JSON data in the following format

{"guid":{"uri":"http://social.yahooapis.com/v1/me/guid","value":"123456789"}}

and here is my parsing code using google-gson

Gson gson=new Gson();
MyGuid myGuid=new MyGuid();
myGuid=gson.fromJson(response.getBody(), MyGuid.class);

public class MyGuid {

public MyGuid() {

}

private String value;

public String getValue() {
    return value;
}

public void setValue(String value) {
    this.value = value;
}

}

but i am getting the value of guid as null. I know i am doing wrong but being new to JSON format is what making me more confused.

Any help in this regard will be helpful.

like image 744
Umesh Awasthi Avatar asked Jul 23 '26 12:07

Umesh Awasthi


1 Answers

Your data structures should reflect the data you are trying to de-serialize.

For example, you could use something of this form:

public class Data {
  private Map<String, String> guid;

  public Map<String, String> getGuid() {
    return guid;
  }

  public void setGuid(Map<String, String> guid) {
    this.guid = guid;
  }

  public static void main(String[] args) {
    String json =
        "{\"guid\":{" + "\"uri\":\"http://social.yahooapis.com/v1/me/guid\","
            + "\"value\":\"123456789\"}}";
    Data data = new Gson().fromJson(json, Data.class);
    System.out.println(data.getGuid()
        .get("uri"));
  }
}

The guid property of the JSON is mapped to the guid property of the Data type. The properties of that object are placed in a Map as strings.

like image 111
McDowell Avatar answered Jul 26 '26 02:07

McDowell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!