Java - 如何在 JSON 数组中获取对象值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22386344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java - How to get object value in JSON array?
提问by redrom
i have a JSON like example below and i'm trying to get some values, for example value of.
我有一个类似于下面的示例的 JSON,我正在尝试获取一些值,例如值。
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.
我怎样才能轻松获得我需要的价值。
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 ).
我尝试找到一些帮助程序(Gson、fast-json 等),但使用起来似乎相当复杂(我想使用 JSON 树直接访问“即时”值或访问值就像一个对象,这意味着.. Object.InnerObject.value )。
So question is how can i do it right?
所以问题是我该怎么做?
Thanks for any advice.
感谢您的任何建议。
采纳答案by vikingmaster
JSON needs to be traversed in order to access id
:
需要遍历 JSON 才能访问id
:
JSONArray results = shipmentData.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
JSONObject shipper = first.getJSONObject("shipper");
Integer id = shipper.getInt("id");
Parse int to string:
将 int 解析为字符串:
String id = String.valueOf(shipper.getInt("id"));