如何使用 getJSONArray 方法访问 json 对象的嵌套元素
Posted
技术标签:
【中文标题】如何使用 getJSONArray 方法访问 json 对象的嵌套元素【英文标题】:How to access nested elements of json object using getJSONArray method 【发布时间】:2013-01-31 16:02:05 【问题描述】:我有一个如下所示的 JSON 响应:
"result":
"map":
"entry": [
"key": "@xsi.type": "xs:string", "$": "ContentA" ,
"value": "fsdf"
,
"key": "@xsi.type": "xs:string", "$": "ContentB" ,
"value": "dfdf"
]
我想访问"entry"
数组对象的值。我正在尝试访问:
RESPONSE_JSON_OBJECT.getJSONArray("entry");
我收到JSONException
。有人可以帮我从上面的 JSON 响应中获取 JSON 数组吗?
【问题讨论】:
您使用哪种语言? 我正在编写一个 Java 类 好的,我忍不住用“java”标记了您的问题,以便其他可以提供帮助的人能够找到它。 【参考方案1】:您必须分解整个对象才能到达entry
数组。
假设REPONSE_JSON_OBJECT
已经是一个已解析的JSONObject
。
REPONSE_JSON_OBJECT.getJSONObject("result")
.getJSONObject("map")
.getJSONArray("entry");
【讨论】:
【参考方案2】:你可以试试这个:
JSONObject result = new JSONObject("Your string here").getJSONObject("result");
JSONObject map = result.getJSONObject("map");
JSONArray entries= map.getJSONArray("entry");
我希望这会有所帮助。
【讨论】:
无法应用字符串【参考方案3】:我建议你使用Gson 库。它允许将 JSON 字符串解析为对象数据模型。请看我的例子:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;
public class GsonProgram
public static void main(String... args)
String response = "\"result\":\"map\":\"entry\":[\"key\":\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\",\"value\":\"fsdf\",\"key\":\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\",\"value\":\"dfdf\"]";
Gson gson = new GsonBuilder().serializeNulls().create();
Response res = gson.fromJson(response, Response.class);
System.out.println("Entries: " + res.getResult().getMap().getEntry());
class Response
private Result result;
public Result getResult()
return result;
public void setResult(Result result)
this.result = result;
@Override
public String toString()
return result.toString();
class Result
private MapNode map;
public MapNode getMap()
return map;
public void setMap(MapNode map)
this.map = map;
@Override
public String toString()
return map.toString();
class MapNode
List<Entry> entry = new ArrayList<Entry>();
public List<Entry> getEntry()
return entry;
public void setEntry(List<Entry> entry)
this.entry = entry;
@Override
public String toString()
return Arrays.toString(entry.toArray());
class Entry
private Key key;
private String value;
public String getValue()
return value;
public void setValue(String value)
this.value = value;
public Key getKey()
return key;
public void setKey(Key key)
this.key = key;
@Override
public String toString()
return "[key=" + key + ", value=" + value + "]";
class Key
@SerializedName("$")
private String value;
@SerializedName("@xsi.type")
private String type;
public String getValue()
return value;
public void setValue(String value)
this.value = value;
public String getType()
return type;
public void setType(String type)
this.type = type;
@Override
public String toString()
return "[value=" + value + ", type=" + type + "]";
程序输出:
Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]
如果你不熟悉这个库,那么你可以在“Gson User Guide”找到很多信息。
【讨论】:
【参考方案4】:我也面临这个问题。所以我用递归解决了。也许会有所帮助。 我创建了方法。我使用了 org.json 库。
public static JSONObject function(JSONObject obj, String keyMain, String newValue) throws Exception
// We need to know keys of Jsonobject
Iterator iterator = obj.keys();
String key = null;
while (iterator.hasNext())
key = (String) iterator.next();
// if object is just string we change value in key
if ((obj.optJSONArray(key)==null) && (obj.optJSONObject(key)==null))
if ((key.equals(keyMain)) && (obj.get(key).toString().equals(valueMain)))
// put new value
obj.put(key, newValue);
return obj;
// if it's jsonobject
if (obj.optJSONObject(key) != null)
function(obj.getJSONObject(key), keyMain, valueMain, newValue);
// if it's jsonarray
if (obj.optJSONArray(key) != null)
JSONArray jArray = obj.getJSONArray(key);
for (int i=0;i<jArray.length();i++)
function(jArray.getJSONObject(i), keyMain, valueMain, newValue);
return obj;
如果你有问题,我可以解释...
【讨论】:
Eric 如果您的keyMain
类似于:key1/key2/key3/key4/0/key
,您如何更新您的值。请注意key4
是列表,所以我从列表中访问0
元素。然后从键更新值。我问这个是因为keyMain
可以在JSON
的不同位置具有相同的值。
keyMain 就像:key1/key2/key3/key4/0/key - 你的意思是像 ("key1.key2.key3",newValue)??按路径搜索?
假设我想将"fieldValue":"Empty"
更新为"fieldValue":"Nikola"
,并且我有key1/key2/key3/key4/0/fieldValue
的位置。这是 Json: "key1": "key2": "key3": "key4":[ "fieldValue":"Empty", "fieldName":"Enter Field Name 1" , "fieldValue":"Empty", "fieldName":"Enter Field Name 2" ]
所以在这个 json 中有 2 个“fieldValue”:“Empty”,你想改变它吗?
如果你想改变它们,只需使用我的代码示例。我想我得到了你需要的东西。我会添加答案。如果它有助于提高我的声誉..【参考方案5】:
这是给尼古拉的。
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException
String[] keyMain = keys.split("\\.");
for (String keym : keyMain)
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext())
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null))
if ((key.equals(keym)) && (js1.get(key).toString().equals(valueMain)))
js1.put(key, valueNew);
return js1;
if (js1.optJSONObject(key) != null)
if ((key.equals(keym)))
js1 = js1.getJSONObject(key);
break;
if (js1.optJSONArray(key) != null)
JSONArray jArray = js1.getJSONArray(key);
JSONObject j;
for (int i = 0; i < jArray.length(); i++)
js1 = jArray.getJSONObject(i);
break;
return js1;
public static void main(String[] args) throws IOException, JSONException
String text = " "key1": "key2": "key3": "key4":[ "fieldValue":"Empty", "fieldName":"Enter Field Name 1" , "fieldValue":"Empty", "fieldName":"Enter Field Name 2" ] ";
JSONObject json = new JSONObject(text);
setProperty(json, "ke1.key2.key3.key4.fieldValue", "nikola");
System.out.println(json.toString(4));
如果对兄弟有帮助,请不要忘记为我的名声)))
【讨论】:
这里的 valueMain 是什么?【参考方案6】:使用 Gson 库尝试此代码并完成工作。
Gson gson = new GsonBuilder().create();
JsonObject job = gson.fromJson(JsonString, JsonObject.class);
JsonElement entry=job.getAsJsonObject("results").getAsJsonObject("map").getAsJsonArray("entry");
String str = entry.toString();
System.out.println(str);
【讨论】:
【参考方案7】:我也会这样尝试
1) 从 JSON 模式创建 Java Bean
2) 使用 JSON 解析器库来避免任何类型的异常
3) 将解析结果转换为从初始 JSON 模式创建的 Java 对象。
下面是一个示例 JSON Schema"
"USD" : "15m" : 478.68, "last" : 478.68, "buy" : 478.55, "sell" : 478.68, "symbol" : "$",
"JPY" : "15m" : 51033.99, "last" : 51033.99, "buy" : 51020.13, "sell" : 51033.99, "symbol" : "¥",
代码
public class Container
private JPY JPY;
private USD USD;
public JPY getJPY ()
return JPY;
public void setJPY (JPY JPY)
this.JPY = JPY;
public USD getUSD ()
return USD;
public void setUSD (USD USD)
this.USD = USD;
@Override
public String toString()
return "ClassPojo [JPY = "+JPY+", USD = "+USD+"]";
public class JPY
@SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
return fifitenM;
public void setFifitenM (double fifitenM)
this.fifitenM = fifitenM;
public String getSymbol ()
return symbol;
public void setSymbol (String symbol)
this.symbol = symbol;
public double getLast ()
return last;
public void setLast (double last)
this.last = last;
public double getSell ()
return sell;
public void setSell (double sell)
this.sell = sell;
public double getBuy ()
return buy;
public void setBuy (double buy)
this.buy = buy;
@Override
public String toString()
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
public class USD
@SerializedName("15m")
private double fifitenM;
private String symbol;
private double last;
private double sell;
private double buy;
public double getFifitenM ()
return fifitenM;
public void setFifitenM (double fifitenM)
this.fifitenM = fifitenM;
public String getSymbol ()
return symbol;
public void setSymbol (String symbol)
this.symbol = symbol;
public double getLast ()
return last;
public void setLast (double last)
this.last = last;
public double getSell ()
return sell;
public void setSell (double sell)
this.sell = sell;
public double getBuy ()
return buy;
public void setBuy (double buy)
this.buy = buy;
@Override
public String toString()
return "ClassPojo [15m = "+fifitenM+", symbol = "+symbol+", last = "+last+", sell = "+sell+", buy = "+buy+"]";
public class MainMethd
public static void main(String[] args) throws JsonIOException, JsonSyntaxException, FileNotFoundException
// TODO Auto-generated method stub
JsonParser parser = new JsonParser();
Object obj = parser.parse(new FileReader("C:\\Users\\Documents\\file.json"));
String res = obj.toString();
Gson gson = new Gson();
Container container = new Container();
container = gson.fromJson(res, Container.class);
System.out.println(container.getUSD());
System.out.println("Sell Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getSell());
System.out.println("Buy Price : " + container.getUSD().getSymbol()+""+ container.getUSD().getBuy());
主要方法的输出是:
ClassPojo [15m = 478.68,符号 = $,最后 = 478.68,卖出 = 478.68,买入 = 478.55]
售价:$478.68
购买价格:478.55 美元
希望这会有所帮助。
【讨论】:
以上是关于如何使用 getJSONArray 方法访问 json 对象的嵌套元素的主要内容,如果未能解决你的问题,请参考以下文章