0

I have this simple json string of two dimensional(2d) arrays and want to convert to JAVA 2d String Array like String[][].

String

"[ [\"case1\",[\"case1-a\"]], [\"case2\",[\"case2-a\",\"case2-b\",\"case2-c\"]] ]"

What is the simplest way to do that ? Been googling around but couldn't find a simple solution. Appreciate any help !

6

1 Answer 1

1

There are probably cleaner ways of doing this with a modern JSON library, but since this way may be easier to understand, I am demonstrating how to do it step by step with the older "Simple JSON" library:

package samplejava;

import java.util.Arrays;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class JsonTest {
public static void main(String[] args) {
    JSONArray rows = (JSONArray) JSONValue.parse("[ [\"case1\",[\"case1-a\"]], [\"case2\",[\"case2-a\",\"case2-b\",\"case2-c\"]] ]");   
    System.out.println("Before: " + rows.toJSONString());
    String[][] result = new String[rows.size()][];
    for(int row = 0; row < rows.size(); row++) {
        JSONArray cols = (JSONArray)((JSONArray) rows.get(row)).get(1);
        String[] temp = new String[cols.size()];
        for(int col=0; col < cols.size(); col++) {
            temp[col] = cols.get(col).toString();
        }
        result[row] = temp;
    }
    System.out.println("After: " + Arrays.deepToString(result));   
}
}

Output:

Before: [["case1",["case1-a"]],["case2",["case2-a","case2-b","case2-c"]]]

After: [[case1-a], [case2-a, case2-b, case2-c]]

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

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.