Reading JSon String with Gson

I searched Google, trying to figure it out, but I can't do it. I have the following json line that returns to the java applet from another source that I need to interact with.

{ "A01": {"Status": "Ready", "Time": "00:00"}, "A02": {"Status": "Ready", "Time": "00:00"}, ...... } 

At the moment, I'm not sure how to use Gson to parse this applet. When I talked with the designers of this program. The json string was designed to be used in php, not java, so when I decrypted it in php, it gave me a nice multi-dimensional associative array.

Any suggestions on this.

+6
java json gson
source share
3 answers

An associative array in PHP is converted to a Map in Java. So, in the eyes of Gson, your JSON is in the format Map<String, Event> , where the Event class has the status and time fields.

 public class Event { private String Status; private String Time; // Add/generate getters, setters and other boilerplate. } 

Yes, uppercase field names are ugly, but what your JSON looks like. Otherwise, you would need to create a custom Gson deserializer .

Here you can convert it.

 Map<String, Event> events = new Gson().fromJson(json, new TypeToken<Map<String, Event>>(){}.getType()); 

A01 , A02 etc. become a Map , and its value becomes an Event value of a Map . You can add another custom deserializer to get time in java.util.Date .

Alternatively, you can also use Map<String, Map<String, String>> .

+7
source share

This link pointed me to something I didn’t even look at. I also forgot to mention in my post that Knowledge is A01, A02, etc. Very important. But the link in the message in which you pointed me to lead me to make this work for me.

 JsonParser parse = new JsonParser(); JsonObject jobj = (JsonObject)parse.parse(status); Set<Map.Entry<String, JsonElement>> map = jobj.entrySet(); Iterator<Map.Entry<String, JsonElement>> iterator = map.iterator(); int size = map.size(); for( int k = 0; k < size; k++ ) { Map.Entry<String, JsonElement> entry = iterator.next(); String key = entry .getKey(); JsonObject jele = (JsonObject)entry.getValue(); } 
+2
source share

If your json was a little different as below:

 { [ {"Status": "Ready", "Time": "00:00"}, {"Status": "Ready", "Time": "00:00"}, ...... ] } 

Gson will be able to convert json into a collection of objects, an object that you will need to define yourself. Therefore, you will need:

 public class myAClass { public String Status; public Double time; //this could be a string/or even a Date I guess, //not sure what data you are expecting //and the colon may cause a problem if parsed as a double } 

And then use it like this:

 Type listType = new TypeToken<List<myAClass>>() {}.getType(); List<myAClass> myAClassList = new Gson().fromJson(json, listType); //where json is yr json string 

Then you can use the list of objects as needed.

(further reading here )

+1
source share

All Articles