0

I followed this tutorial on how to decode json with java: https://code.google.com/p/json-simple/wiki/DecodingExamples

In my project i get info_string:

   {"server_ip":"http://localhost:3000/","device_id":14}

that i would like to decode: I tried:

  System.out.println(info_string);
 => {"server_ip":"http://localhost:3000/","device_id":14}
  Object obj = JSONValue.parse(info_string);
  System.out.println(obj);
 => null
  JSONArray array=(JSONArray)obj;
 => null
  System.out.println(array);

As you can see the array and obj variable are null and contain no data! What do i wrong? Thanks

John Smith
  • 6,105
  • 16
  • 58
  • 109
  • Any non-printable/invisible characters in the String you got from the server? `String info_string = "\u0000{\"server_ip\":\"http://localhost:3000/\",\"device_id\":14}";` would demonstrate the behavior you are seeing. Otherwise it's working fine for me (until you try to cast `obj` to a `JSONArray` but that's another story). – Alexis C. Dec 13 '14 at 10:21
  • @ZouZou what would you do to fix this problem? Trim() the string? – John Smith Dec 13 '14 at 10:28
  • @ZouZou you are right `info_string.trim()` works! Could you please write an answer? – John Smith Dec 13 '14 at 10:29
  • @ZouZou and hoy can i get the single values? For example `device_id` from this `obj`? Thanks! – John Smith Dec 13 '14 at 10:33

1 Answers1

1

There are certainly non-printable/invisible characters. I suggest you to use a regular expression to remove them, because if you String looks like

String info_string = "   {\"server_ip\":\u0000\"http://localhost:3000/\",\"device_id\":14}";

trim() will do nothing.

So try with:

Object obj = JSONValue.parse(info_string.replaceAll("\\p{C}", ""));

and how can i get the single values? For example device_id from this obj?

In your case, parse will return a JSONObject, so you can cast the result, and then use the get method to get the value associated with the corresponding key:

JSONObject obj = (JSONObject) JSONValue.parse(info_string);
String serverIp = (String) obj.get("server_ip"); //http://localhost:3000/    
long deviceId = (Long) obj.get("device_id"); //14
Community
  • 1
  • 1
Alexis C.
  • 91,686
  • 21
  • 171
  • 177