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 !

GURU-MVG
  • 161
  • 5
  • 13
  • You could use regex. http://www.vogella.com/tutorials/JavaRegularExpressions/article.html Here is a good example how to use it – Z3RP Sep 13 '18 at 14:21
  • No RegExp. I'm looking for a simple json parser. – GURU-MVG Sep 13 '18 at 14:24
  • 2
    The example you provided looks to me more like a map. Also look here: https://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – Korashen Sep 13 '18 at 14:25
  • No its not a map, as i mentioned it is a simple string of nested 2d/3d arrays – GURU-MVG Sep 13 '18 at 14:35
  • https://code.google.com/archive/p/quick-json/ Quick Json Parser is good for that but i think you must edit the string a bit – Z3RP Sep 14 '18 at 06:09
  • @GURU-MVG was your question [answered](http://stackoverflow.com/help/someone-answers)? – Patrick Parker Sep 14 '18 at 14:28

1 Answers1

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]]

Community
  • 1
  • 1
Patrick Parker
  • 4,863
  • 4
  • 19
  • 51