使用Java访问JSONArray中的项的成员

时间:2021-10-24 15:54:35

I'm just getting started with using json with java. I'm not sure how to access string values within a JSONArray. For instance, my json looks like this:

我刚开始使用json和java。我不知道如何在JSONArray中访问字符串值。例如,我的json是这样的:

{
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501
        "loc": "NEW YORK STATE"
      }
    ]
  }
}

my code:

我的代码:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));
JSONObject locs = req.getJSONObject("locations");
JSONArray recs = locs.getJSONArray("record");

I have access to the "record" JSONArray at this point, but am unsure as to how I'd get the "id" and "loc" values within a for loop. Sorry if this description isn't too clear, I'm a bit new to programming.

此时我可以访问“record”JSONArray,但是我不确定如何在for循环中获得“id”和“loc”值。对不起,如果这个描述不太清楚,我对编程有点陌生。

6 个解决方案

#1


183  

Have you tried using [JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)), and [JSONArray.length()](http://json.org/javadoc/org/json/JSONArray.html#length()) to create your for-loop:

您是否尝试过使用[JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int))和[JSONArray.length()](http://json.org/javadoc/org/json/json/json/jsonarray.html)来创建for- length()

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

#2


4  

An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:

一个org.json。JSONArray不是iterable。下面是我如何处理net.sf.json.JSONArray中的元素:

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

Works great... :)

伟大的工作…:)

#3


2  

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

Java 8已经上市近20年了,以下是迭代org.json的方法。带有java8流API的JSONArray。

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

如果迭代只是一次,(不需要。collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

#4


1  

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

通过查看代码,我感觉您在使用JSONLIB。如果是这样,请查看下面的代码片段,将json数组转换为java数组。

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

#5


0  

In case it helps someone else, I was able to convert to an array by doing something like this,

如果它能帮助别人,我可以通过这样的操作转换成一个数组,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

…或者你应该能得到长度

((JSONArray) myJsonArray).toArray().length

#6


-1  

HashMap regs = (HashMap) parser.parse(stringjson);

HashMap regs = (HashMap) parser.parse(stringjson);

(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

(字符串)((HashMap)regs.get(“firstlevelkey”)). get(" secondlevelkey ");

#1


183  

Have you tried using [JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int)), and [JSONArray.length()](http://json.org/javadoc/org/json/JSONArray.html#length()) to create your for-loop:

您是否尝试过使用[JSONArray.getJSONObject(int)](http://json.org/javadoc/org/json/JSONArray.html#getJSONObject(int))和[JSONArray.length()](http://json.org/javadoc/org/json/json/json/jsonarray.html)来创建for- length()

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}

#2


4  

An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.JSONArray:

一个org.json。JSONArray不是iterable。下面是我如何处理net.sf.json.JSONArray中的元素:

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

Works great... :)

伟大的工作…:)

#3


2  

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

Java 8已经上市近20年了,以下是迭代org.json的方法。带有java8流API的JSONArray。

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

如果迭代只是一次,(不需要。collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });

#4


1  

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

通过查看代码,我感觉您在使用JSONLIB。如果是这样,请查看下面的代码片段,将json数组转换为java数组。

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

#5


0  

In case it helps someone else, I was able to convert to an array by doing something like this,

如果它能帮助别人,我可以通过这样的操作转换成一个数组,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

…或者你应该能得到长度

((JSONArray) myJsonArray).toArray().length

#6


-1  

HashMap regs = (HashMap) parser.parse(stringjson);

HashMap regs = (HashMap) parser.parse(stringjson);

(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

(字符串)((HashMap)regs.get(“firstlevelkey”)). get(" secondlevelkey ");