Reputation: 594
Can anyone please help me to convert this JSON to Java Object. I usually use GSON, but it seem this time it is not working for me. The problem is that I want to create an Object that contains
Class JsonGotText{
String status;
List<Object> result;
}
But all the Object in List is all difference properties... So I don know how to do to let Gson Map it correctly
{
"status": 0,
"result": {
"1346053628": {
"type": "default",
"decorated_time": 1346053628,
"guidOwner": 13716,
"friendGuid": 3264,
"action_type": "friend",
"summary": " is now a friend with ",
"annotation": null,
"group": ""
},
"1346051675": {
"type": "event",
"decorated_time": 1346051675,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
},
"1346048488": {
"type": "event",
"decorated_time": 1346048488,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
}
}
}
Upvotes: 0
Views: 217
Reputation: 55866
Try using
Class JsonGotText{
String status;
HashMap<String, Object> result;
}
If performance is not key criteria here. You better use 'JSONObject' without worrying the structure of JSON String.
Ideally, you should write a POJO. Say EventPOJO
that has attributes same as as each result object holds and then make the Java class as
Class JsonGotText{
String status;
HashMap<String, EventPOJO> result;
}
you may have to use a type token see here, but will save your efforts later.
Update
It seems the sentence above sounds confusing. Here is clarification what I wanted EventPOJO
to represent to. The EventPOJO will represents things like
{
"type": "event",
"decorated_time": 1346048488,
"guidOwner": 90,
"title": null,
"action_type": "event_relationship",
"summary": "river:event_relationship:object:event",
"annotation": null,
"group": ""
}
Update1 @LalitPoptani asked for exact working code. Here it is!
Here is an working example:
public class Test {
private static String json =
"{"+
"\"status\": 0,"+
"\"result\": {"+
"\"1346053628\": {"+
"\"type\": \"default\","+
"\"decorated_time\": 1346053628,"+
"\"guidOwner\": 13716"+
"},"+
"\"1346051675\": {"+
"\"type\": \"event\","+
"\"decorated_time\": 1346051675,"+
"\"guidOwner\": 90"+
"},"+
"\"1346048488\": {"+
"\"type\": \"event\","+
"\"decorated_time\": 1346048488,"+
"\"guidOwner\": 90"+
"}"+
"}" +
"}";
public static class Event{
String type;
Long decorated_time;
Integer guidOwner;
}
public static class JSON{
Integer status;
HashMap<Long, Event> result;
}
public static void main(String[] args){
Gson gson = new Gson();
System.out.println("JSON: " + json);
JSON j = gson.fromJson(json, JSON.class);
for(Entry<Long, Event> e: j.result.entrySet()){
System.out.println(e.getKey() + ": " + e.getValue().guidOwner);
}
}
}
Upvotes: 1