简体   繁体   中英

Deserializing JSON string in android

I have JSON String that read as below

{   "Status":"Clear",    "Class": [{  <br>
        {"name":"personA", "available" : 1}, <br>
       {"name":"personB", "available" : 0}, <br>
       {"name":"personC", "available" : 0}, <br>
        {"name":"personD", "available" : 1} <br>
         }] }

How do I deserialize the JSON String above?

I got the idea of using JSONObject to take in whole JSON String into it but no idea how to get the arraylist of object (the list of Class object) and assign to a arraylist<Class>.

Guidance and help are much appreciated.

UPDATED :

SOLVED AND SOLUTION SHOWN

I have solved this question but I think I have to explain how and why I used such solution.

So to further explain my question, this is an json string that originally an object that got serialized and sent from a webservice to my apps.

the original object is like this :

 public class StatusJson
     {
         public String Status { get; set; }
         public List<Class> Class { get; set; }
     }

So what I have to do is just declare an exactly same class in my android then use this code

statusJson  statusJSON=g.fromJson(JSonString,StatusJson.class);

which will automatically parse the json string to the exact same class format.

Hope this will help you guys too if you are directly sending a JSON serialized class like me.

I suggest you to check Gson library .

You can create a class with anotations

private class ClassObj {
@SerializedName("personA") 
private final String personA;
....
}

And then

ClassObj object = gson.fromJson(jsonString, ClassObj.class);

It can be complicated object, which contain other gson objects or Collection. Try.

I believe this is an invalid Json. Your class attribute is an array and an object.

Look at the API's of JSONObject and JSONArray .

You should be able to figure it out from there. You just create a JSONObject out of the string:

ex. JSONObject jsonAsObj = new JSONObject(my_json_string) ;

Then use JSONArray classArray = jsonAsObject.getJSONArray("Class"); to get your array...

As far as converting it to an ArrayList, you need to create your type and traverse the JSONArray and create objects from it, and add them to your ArrayList. Or you could look into another helper library, like GSON .

You need to use GSON library for example:

@SerializedName("studentName") public String name;

There is a need to add a somewhat missing feature in the above first(thealeksandr)'s answer:

 Gson gson = new GsonBuilder().create();

You can now use this instantiated object gson in the above ClassObj object = gson.fromJson(jsonString, ClassObj.class); To do this simply use GsonBuilder class in the Gson Library as I just demonstrated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM