简体   繁体   English

从JSONArray中的JSONArray获取JSONObjects

[英]getting JSONObjects from JSONArray within a JSONArray

I'm new to json with java and I have a json that looks like this: 我是java的json新手,并且我有一个看起来像这样的json:

[{
    "color": red,
    "numbers": [
        "8967",
        "3175",
        "1767"
    ],
}, {
    "color": blue,
    "numbers": [
        "1571",
        "5462",
        "54"
    ]
}] 

And code to try and extract the colors and numbers: 并尝试提取颜色和数字的代码:

while(i<jsonArray.size()){
JSONObject object = (JSONObject) jsonArray.get(i);
colors = object.get("color");
numbers.add(object.get("numbers");

The colors get extracted fine but my problem is I am trying to extract the numbers and place them 1 by 1 in an array but instead of placing them like this: 颜色可以很好地提取,但是我的问题是我试图提取数字并将它们一对一地放置在数组中,而不是像这样放置它们:

numbers[0]="8967"
numbers[1]="3175"

they get placed like this: 他们被这样放置:

numbers[0]={"8967","3175","1767"}

How can I get them placed 1 by 1 as above? 我如何如上所述将它们一一放置?

You asked for the nunbers field, its a JSON array so it adds the JSON array to the forst cell. 您要求输入nunbers字段,它是一个JSON数组,因此将JSON数组添加到了Forst单元格中。 Try to run through the values of the "numbers" array. 尝试遍历“数字”数组的值。 Or not sure about that - try using the addAll method instead of add. 对此不确定 -尝试使用addAll方法而不是add。

You can try to use this code: 您可以尝试使用以下代码:

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JSONParserExample {

    public static void main(String[] args) {
        JSONArray jsonArray = null;
        try (BufferedReader input = new BufferedReader(new FileReader("src/main/resources/example.json"))) {
            JSONParser parser = new JSONParser();
            jsonArray = (JSONArray) parser.parse(input);
        } catch (IOException | ParseException e) {
            System.out.println("Failed to load properties from file.");
        }


        Map<String, List<String>> values = new HashMap<>();
        for (Object obj : jsonArray) {
            JSONObject jsonObj = (JSONObject) obj;

            String color = (String) jsonObj.get("color");
            JSONArray numbersJSON = (JSONArray) jsonObj.get("numbers");

            List<String> numbers = new ArrayList<>();
            for (Object o : numbersJSON) {
                numbers.add((String) o);
            }
            values.put(color, numbers);
        }

        for (Map.Entry<String, List<String>> entry : values.entrySet()) {
            System.out.printf("[Key, Value]: %s, %s \n", entry.getKey(),  entry.getValue());
        }
    }
}

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

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