user4267868
user4267868

Reputation: 45

Read Json file using Java

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

Upvotes: 0

Views: 476

Answers (2)

biggvsdiccvs
biggvsdiccvs

Reputation: 299

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.

Upvotes: 1

wassgren
wassgren

Reputation: 19221

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>

Upvotes: 1

Related Questions