Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse JSON of two dimensional array in JAVA

Problem is, my JSON string looks like this:

jsonString =  [["1","100"],["2","200"],["3","300"]]

I need to make a two dimensional array out of it in Java. If I write

JSONObject jObs = new JSONObject(jsonString);

I get the following error:

A JSONObject text must begin with '{' at character 1 of [["1 ...

How can I parse a two dimensional array out of this string? Thanks in advance.

like image 780
QuestionEverything Avatar asked Nov 20 '25 03:11

QuestionEverything


1 Answers

The JSON you've got is for an array, not an object. You probably want

JSONArray array = new JSONArray(jsonString);

Full sample code:

import org.json.*;

public class Test {
    public static void main(String[] args) {
        String json = "[[\"1\",\"100\"],[\"2\",\"200\"],[\"3\",\"300\"]]";
        JSONArray array = new JSONArray(json);
        JSONArray first = array.getJSONArray(0);
        System.out.println(first.getString(1)); // Prints 100
    }
}
like image 111
Jon Skeet Avatar answered Nov 22 '25 16:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!