0

I'm new to json with java and I have a json that looks like this:

[{
    "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?

2 Answers 2

0

You asked for the nunbers field, its a JSON array so it adds the JSON array to the forst cell. Try to run through the values of the "numbers" array. Or not sure about that - try using the addAll method instead of add.

Sign up to request clarification or add additional context in comments.

Comments

0

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());
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.