3

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.

2
  • Please post a SSCCE or at least the actual code of your MyGuid class (except getters/setters). Commented Nov 27, 2011 at 15:33
  • Before you worry about mixing in your domain classes etc., hard code the JSON as a string, parse that with Gson, get that working, and then worry about the more complicated case of getting JSON from a response object, hooking it up to your class, etc. Commented Nov 27, 2011 at 15:33

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.