JSON-遍历JSONArray

JSON-遍历JSONArray,第1张

JSON-遍历JSONArray

更改

JSonObject objects = getArray.getJSonArray(i);

JSonObject objects = getArray.getJSonObject(i);

或者

JSonObject objects = getArray.optJSonObject(i);

取决于您使用的是JSON到/来自Java的库。(看起来

getJSONObject
将为您工作。)

然后,要访问“对象”中的字符串元素,请

JSONObject
按元素名称将其取出。

String a = objects.get("A");

如果需要中的元素名称,则

JSONObject
可以使用静态实用程序方法
JSONObject.getNames(JSONObject)
来实现。

String[] elementNames = JSONObject.getNames(objects);

“获取第一个元素的值和最后一个元素的值。”

如果“ element”是指数组中的组件,请注意第一个组件在索引0处,最后一个组件在index处

getArray.length() - 1


我想遍历数组中的对象并获取其组件和值。在我的示例中,第一个对象具有3个成分,scond具有5个成分,第三个具有4个成分。我想遍历它们中的每一个并获得其组件名称和值。

以下代码正是这样做的。

import org.json.JSONArray;import org.json.JSONObject;public class Foo{  public static void main(String[] args) throws Exception  {    String jsonInput = "{"JObjects":{"JArray1":[{"A":"a","B":"b","C":"c"},{"A":"a1","B":"b2","C":"c3","D":"d4","E":"e5"},{"A":"aa","B":"bb","C":"cc","D":"dd"}]}}";    // "I want to iterate though the objects in the array..."    JSonObject outerObject = new JSonObject(jsonInput);    JSonObject innerObject = outerObject.getJSonObject("JObjects");    JSonArray jsonArray = innerObject.getJSonArray("JArray1");    for (int i = 0, size = jsonArray.length(); i < size; i++)    {      JSonObject objectInArray = jsonArray.getJSonObject(i);      // "...and get thier component and thier value."      String[] elementNames = JSONObject.getNames(objectInArray);      System.out.printf("%d ELEMENTS IN CURRENT OBJECT:n", elementNames.length);      for (String elementName : elementNames)      {        String value = objectInArray.getString(elementName);        System.out.printf("name=%s, value=%sn", elementName, value);      }      System.out.println();    }  }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5615167.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-15
下一篇2022-12-15

发表评论

登录后才能评论

评论列表(0条)

    保存