-2

I'm setting up a java game server request handler that get json messages and send back relevant json message as response. In some cases I need to send 2 dimensional String array as the game board. I'm having a problem to do that using json-simple. Further more, how to parse it to a board in the client side afterwards? Thanks.

char[][] charArray; //initialised  
JSONObject jsonOut = new JSONObject();
ObjectOutputStream writer = new ObjectOutputStream(socket.getOutputStream());
JSONArray ja = new JSONArray() ;

ja.add(charArray);
jsonOut.put("board", ja);
writer.writeObject(jsonOut);

getting exception while ja.add(charArray);

LostKatana
  • 468
  • 9
  • 22
Niv Lusty
  • 33
  • 8

2 Answers2

1

You are attempting to add an entire char[][] array as a single element in JSONArray. You need to create a multi-dimensional JSONArray and map the char[][] character-by-character:

JSONArray jsonArray = new JSONArray();
for (char[] ca : charArray) {
  JSONArray arr = new JSONArray();
  for (char c : ca) {
    arr.add(Character.toString(c)); // or some other conversion
  }
  jsonArray.add(arr);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

You need to have a JsonArray of JsonArrays, the same way your String[][] is an array of arrays.

ggfpc
  • 86
  • 8