简体   繁体   English

如何解析此JSON对象

[英]How to parse this JSON object

This is the json response from my server . 这是我服务器的json响应。 How can i parse it and store it in HashMap? 我如何解析并将其存储在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: 我是android中的新手,但也许您可以执行以下操作:

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. 我为自己的JSON解析器做了类似的事情。 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. 我建议您看一下gson库,它确实非常容易将JSON解析为表示数据的对象。 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. 因此,您可以创建一个Record对象,并使用带有数字,说明的公共成员变量,然后使用gson将JSON解析为一个对象数组。

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

Add the .jar to your libs folder and then use it like this: 将.jar添加到您的libs文件夹,然后像这样使用它:

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 org.json软件包包含在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 . 然后可以将每个属性作为Java属性进行访问,例如json_object.property It will throw a JSONException if the parsing fails for some reason (ie, invalid JSON). 如果解析由于某种原因而失败(例如,无效的JSON),它将抛出JSONException

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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