[英]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 我按照本教程讲解了如何使用Java解码JSON: https : //code.google.com/p/json-simple/wiki/DecodingExamples
In my project i get info_string
: 在我的项目中,我得到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! 如您所见, array
和obj
变量为null
,不包含任何数据! 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看起来像
String info_string = " {\"server_ip\":\u0000\"http://localhost:3000/\",\"device_id\":14}";
trim()
will do nothing. trim()
不会执行任何操作。
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? 例如来自此obj的device_id?
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: 在您的情况下, parse
将返回JSONObject
,因此您可以JSONObject
结果,然后使用get
方法获取与相应键相关联的值:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.