简体   繁体   中英

How to parse this JSON object

This is the json response from my server . How can i parse it and store it in HashMap? Please help me.

 {'records':
     [{
        'number':165, 
        'description': 'abcd'
      },
      {
         'number':166, 
         'description': 'ab'
      },
      {
         'number':167, 
         'description': 'abc'
      }]
  }

im new in android but maybe you can do something like this:

JSONObject JsonObject = new JSONObject(json);
JSONArray JsonArray_ = JsonObject .getJSONArray("records");

for (int i = 0; i < numberOfItems; i++) {
JSONObject record= JsonArray_photo.getJSONObject(i);    
parsedObject.number = record.getString("number"); //its the same for all fields        
map.add(parsedObject);
}

I done something like that for my own JSON parser. hope this helps. cheers

I suggest you look at the gson library, which makes it very easy indeed to parse JSON into an object representing the data. So you could create a Record object, with public member variables for number, description, and then use gson to parse the JSON into an object array.

http://code.google.com/p/google-gson/

Add the .jar to your libs folder and then use it like this:

Record[] records = new GsonBuilder().create().fromJson(jsonString,Record[].class)
int number = record[0].number;

The org.json package is included in Android: http://developer.android.com/reference/org/json/package-summary.html

Use is simple:

JSONObject json_object = new JSONObject(String json_string);

Each property can then be accessed as a Java property, eg json_object.property . It will throw a JSONException if the parsing fails for some reason (ie, invalid JSON).

您可以使用Gson库,也可以在softwarepassion.com上找到完整的教程

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