简体   繁体   中英

Problems decoding JSON with json-simple

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

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

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