0

I am able to convert simple Json into java objects using Google Gson. The issue is I am not able to convert this specific type of response to a java object. I think this is due to the fact that I am not sure how to actually model the java classes for it. The following is the Json:

{
"List": {
    "Items": [
        {
            "comment": "comment",
            "create": "random",
            "ID": 21341234,
            "URL": "www.asdf.com"
        },
        {
            "comment": "casdf2",
            "create": "rafsdfom2",
            "ID": 1234,
            "Url": "www.asdfd.com"
        }
    ]
},
"related": {
    "Book": "ISBN",
    "ID": "id"
}}
gvar
  • 29
  • 1
  • 1
  • 6
  • Can you share your java class for this Json representation? And btw this json is not complex – Juned Ahsan Jul 31 '13 at 10:01
  • That's the problem. The question says that s/he can't work out how to model the classes. I think. – Joe Jul 31 '13 at 10:13
  • there are generators out there which will generate the classes for you. See this question http://stackoverflow.com/questions/1957406/generate-java-class-from-json – Sebastian van Wickern Jul 31 '13 at 11:07

1 Answers1

0

I haven't worked with Gson specifically, but I have worked with JSON / Java conversion in Jersey and JAXB. I would say that the easiest way to translate the JSON text is to map every {..} to a Class and [..] to a List.

For example:

Class Data {
    HistoryListClass HistoryList;
    Relation related;
}

Class HistoryListClass {
    List<History> history;
}

Class History {
    String comment;
    String create;
    int ID;
    String ttURL;
}

Class Relation {
    String book;
    String ID;
}

See also: Converting JSON to Java

The "HistoryList" element in the JSON code should probably be written "historyList", and just looking at the code given, I suggest you change it to contatain the list of "History" objects directly.

Community
  • 1
  • 1
Icermann
  • 181
  • 3
  • This work fine, but @Icermann`s fields names not identical to the question`s structure. – Michael Cheremuhin Jul 31 '13 at 11:01
  • After that, call "Data data = new Gson().fromJson( inputJsonString, Data.class ); – Michael Cheremuhin Jul 31 '13 at 11:02
  • why is it not identical to the question's structure? – gvar Jul 31 '13 at 13:18
  • This code won't work, because attribute names in your class structure **must match exactly** the names of the JSON fields... So you need to use `HistoryList` and `ID` as names of the attributes... Otherwise you can use the annotation `@SerializedName("HistoryList")`... – MikO Jul 31 '13 at 15:10
  • The code has been changed tp match the JSON format, although the names doesn't adhere to Java naming conventions. MikO's suggestion of @SerializedName sounds like a good idea. – Icermann Jul 31 '13 at 20:19