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

4
  • 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). Commented Dec 13, 2014 at 10:21
  • @ZouZou what would you do to fix this problem? Trim() the string? Commented Dec 13, 2014 at 10:28
  • @ZouZou you are right info_string.trim() works! Could you please write an answer? Commented Dec 13, 2014 at 10:29
  • @ZouZou and hoy can i get the single values? For example device_id from this obj? Thanks! Commented Dec 13, 2014 at 10:33

1 Answer 1

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