我是在 Java 中使用 json-simple 库的新手,并且我已经经历过 encoding和 decoding sample 。复制编码示例很好,但我无法让解码示例与混合类型 JSON 一起使用。
我的问题之一是库中有太多的类没有正确记录,并且我没有源代码(以便能够通读并理解它们的用途)。因此,我很难理解如何使用这些类。
读完这个例子后:
String jsonText = "{\"first\": 123, \"second\": [4, 5, 6], \"third\": 789}";
JSONParser parser = new JSONParser();
ContainerFactory containerFactory = new ContainerFactory(){
public List creatArrayContainer() {
return new LinkedList();
}
public Map createObjectContainer() {
return new LinkedHashMap();
}
};
try {
Map json = (Map)parser.parse(jsonText, containerFactory);
Iterator iter = json.entrySet().iterator();
System.out.println("==iterate result==");
while(iter.hasNext()) {
Map.Entry entry = (Map.Entry)iter.next();
System.out.println(entry.getKey() + "=>" + entry.getValue());
}
System.out.println("==toJSONString()==");
System.out.println(JSONValue.toJSONString(json));
} catch(ParseException pe) {
System.out.println(pe);
}
来自 json-simple official decoding tutorial ,我尝试解码这个 JSON:
{
"stat":{
"sdr": "MAC address of FLYPORT",
"rcv": "ff:ff:ff:ff:ff:ff",
"time": "0000000000000",
"type": 0,
"subt": 0,
"argv": [
{"type": "6","val": "NetbiosName"},
{"type": "6","val": "MACaddrFlyport"},
{"type": "6","val": "FlyportModel"},
{"type": "1","val": id}
]
}
}
我正在编写以下代码来解码:
String jsonString = "{\"stat\":{\"sdr\": \"aa:bb:cc:dd:ee:ff\",\"rcv\": \"aa:bb:cc:dd:ee:ff\",\"time\": \"UTC in millis\",\"type\": 1,\"subt\": 1,\"argv\": [{1,2},{2,3}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON);
但是这不起作用。事实上,我也无法让未经修改的示例工作,并且原始作者也没有解释他们的代码。
如图所示,解码此 JSON 的最简单方法是什么?
最佳答案
这是最好、最简单的代码:
public class test
{
public static void main(String str[])
{
String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject newJSON = jsonObject.getJSONObject("stat");
System.out.println(newJSON.toString());
jsonObject = new JSONObject(newJSON.toString());
System.out.println(jsonObject.getString("rcv"));
System.out.println(jsonObject.getJSONArray("argv"));
}
}
library definition of the json files are given here 。它与发布的库不同 here ,即您发布的。您发布的内容是simple json library我用过this library .
您可以download the zip 。然后在您的项目中创建一个package
,名称为org.json。并将所有下载的代码粘贴到那里,然后玩得开心。
我觉得这是最好也是最简单的 JSON 解码。
关于java - 使用 json-simple 库在 Java 中解码 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57934194/