我遵循了有关如何使用 java 解码 json 的教程:https://code.google.com/p/json-simple/wiki/DecodingExamples
在我的项目中我得到info_string
:
{"server_ip":"http://localhost:3000/","device_id":14}
我想解码:我尝试过:
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);
如您所见,array
和 obj
变量为 null
并且不包含任何数据!
我做错了什么?谢谢
最佳答案
肯定有不可打印/不可见的字符。我建议您使用regular expression to remove them ,因为如果你的字符串看起来像
String info_string = " {\"server_ip\":\u0000\"http://localhost:3000/\",\"device_id\":14}";
trim()
不会执行任何操作。
所以尝试:
Object obj = JSONValue.parse(info_string.replaceAll("\\p{C}", ""));
<小时/>
and how can i get the single values? For example device_id from this obj?
在您的情况下,parse
将返回一个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
关于java - 使用 json-simple 解码 JSON 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457701/