Reputation: 6269
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
Upvotes: 0
Views: 146
Reputation: 93872
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
Upvotes: 1