简体   繁体   中英

Parsing arrays in Json using Gson

Parsing arrays in json using Gson. I have this following json and trying to parse it.

{
"success": true,
"message": "success message",
"data": [
    {
        "city": "cityname",
        "state": "statename",
        "pin": 0,
         "name" :{
                   "firstname" : "user"
                 },
         "id" :"emailid"
    }],
"status" : "done"
}

So, I have created pojo classes using http://www.jsonschema2pojo.org/

Now, I want to parse the array, for value "city".This is how I did but not sure what is wrong here.

 Gson gson = new Gson();
 Records obj = gson.fromJson(response,Records.class);
 try {

     JSONArray jsonArray = new JSONArray(obj.getData());

     for(int i=0; i<jsonArray.length(); i++)
     {
          JSONObject object = jsonArray.getJSONObject(i);
          String city = object.getString("city");
          AlertDialog.Builder dialog = new AlertDialog.Builder(this);
          dialog.setMessage(city);
          dialog.show();

      }}

    catch (Exception e) {
            e.printStackTrace();
        }

And this is what getData() is defined in model class:

public class Records {

//////
private ArrayList<Datum> data = null;
public ArrayList<Datum> getData() {
    return data;
}

this is not required:

try {

 JSONArray jsonArray = new JSONArray(obj.getData());
 ...
}
   catch
...

you just need to do

Records obj = gson.fromJson(response,Records.class);

and then

obj.getData();

would be great if you check that getData() is not null, beacuse something xould go wrong when deserialising


for getting the city: use the getter in the Datum class, you have at the end a list of those obejcts when you call getData

public String getCity() {
return city;
}

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