简体   繁体   English

在Java中读取JSON双维数​​组

[英]Read JSON double dimensional array in Java

I'm trying to get a string from a JSONObject. 我正在尝试从JSONObject获取一个字符串。

My JSON looks like this : 我的JSON看起来像这样:

{
    "agent":
    [
        {"name":"stringName1", "value":"stringValue1"},
        {"name":"stringName2", "value":"stringValue2"}
    ]
}

I want to get the values from stringName1 and stringName2. 我想从stringName1和stringName2获取值。 So first, I tried to get the "agent" using this : 首先,我尝试使用此代码获取“代理”:

JSONObject agent = (JSONObject) jsonObject.get("agent");

However, this throws me an error. 但是,这会引发一个错误。

Have you got any idea on how to process ? 你对如何处理有任何想法吗?

You're trying to parse a JSON array into a JSON object. 您正在尝试将JSON数组解析为JSON对象。 Of course it's going to give you errors. 当然它会给你错误。

Try this instead: 试试这个:

JSONArray agent = jsonObject.getJsonArray("agent");

// To get the actual values, you can do this:
for(int i = 0; i < agent.size(); i++) {
    JSONObject object = agent.get(i);
    String value1 = object.get("name");
    String value2 = object.get("value");
}
 String Json=" { agent: [ {name:stringName1, value:stringValue1},{name:stringName2, value:stringValue2}]}";

You are parsing Jsonarray in to JsonObject that is why you are getting error. 您正在将Jsonarray解析为JsonObject,这就是您收到错误的原因。

JSONObject obj = new JSONObject(Json);
JSONArray array = obj.getJSONArray("agent");

 for(int i = 0 ; i < array.length() ; i++)
       {
   String strngNameOne=array.getJSONObject(i).getString("name");
   String stringNameTwo=array.getJSONObject(i).getString("value");
   //System.out.println(array.getJSONObject(i));
        }

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

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