Java-如何获取JSON数组中的对象值?
我下面有一个类似JSON的示例,并且我试图获取一些值,例如of的值.
i have a JSON like example below and i'm trying to get some values, for example value of.
results.shipper.id
{
"results": [
{
"updated": false,
"notification": false,
"some_data": {
"id": 15989,
"pieces": 0,
},
"shipper": {
"updated": false,
"notification": false,
"id": 1587,
"parent": {
"updated": false
},
我正试图通过这种方式获得价值:
I'm trying to get value by this way:
String test = shipmentData.getJSONObject("shipper").getString("id");
但是它总是抛出异常.我认为,该异常是由于我无法通过结果"数组访问值而引起的.
But it always throws a exception. I think, that exception is caused because of the i am not accessing to the values via "results" array.
我如何轻松获得所需的价值.
How can i easy access to the value what i need.
我试图找到一些助手(Gson,fast-json等),但是使用起来似乎很复杂(我想使用JSON树直接访问即时"值或访问类似于对象的值,则表示.. Object.InnerObject.value).
I tried find some helpers (Gson, fast-json, etc..) but it seems to be a quite complicated for using (i would like to work with JSON tree for direct access to values "on-the-fly" or access to values like to a object, it means.. Object.InnerObject.value ).
所以问题是我该怎么做?
So question is how can i do it right?
谢谢您的任何建议.
需要遍历JSON才能访问id
:
JSON needs to be traversed in order to access id
:
JSONArray results = shipmentData.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
JSONObject shipper = first.getJSONObject("shipper");
Integer id = shipper.getInt("id");
将int解析为字符串:
Parse int to string:
String id = String.valueOf(shipper.getInt("id"));