0

I have a JSON file look like:

[[10,5,0,...,1,8], [3,6,3,...,6,3], [15,7,2,...,1,1], [8,7,4,...,8,3], [...], [6,11,0,...,5,1]]

nXm matrix. (n and m is unknown).

I want to manipulate(do calculation) on Java. I was thinking to read/input it into 2D array in Java. Do I treat JSON file same as text file using BufferReader or is there a easier way to read/manipulate it on Java? How should I create 2d array with unknown size?

Thank you

1
  • 1
    There are several Java libraries that will parse JSON into objects. Commented Jan 22, 2015 at 23:56

2 Answers 2

1

You could use this library:

http://www.json.org/java/

Then you can read the file into a String used a BufferedReader, close the reader and do something like this:

JSONArray ja = new JSONOArray(string);
int[][] result = new int[ja.length()][];
for (int i = 0; i < ja.length(); i++) {
    JSONAarray ja2 = ja.getJSONArray(i);
    result[i] = new int[ja2.length()];
    for (int j = 0; j < ja2.length(); j++) {
        result[i][j]=ja2.getInt(j);
    }
}

I haven't tested this code, and you also might want to add some error checking and extract local variables, depending on how sure you are the file is in the right format. This does not assume your file contains a rectangular matrix.

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

Comments

1

If you have JSON as input and want to convert it to a Java 2D array you can easily convert your JSON input using the Jackson library. Jackson can convert JSON to POJOs and POJOs to JSON and this is called deserialization/serialization.

The main class used for mapping between JSON and POJOs is the ObjectMapper. To convert from a JSON String to a 2D array of ints the following Java code can be used:

final String json = "[[1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]";

// Create a Jackson mapper
ObjectMapper mapper = new ObjectMapper();

// Map the JSON to a 2D array
final int[][] ints = mapper.readValue(json, int[][].class);

The only dependencies required to run Jackson is:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.0</version> <!-- At the time of writing -->
</dependency>

1 Comment

I am very new to Json file. I am not sure what you mean by dependency

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.