简体   繁体   中英

How to write 2 two-dimensional array to json object in java using json-simple?

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);

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);
}

你需要有一个 JsonArray 的 JsonArray,就像你的 String[][] 是一个数组数组一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM