我是使用Java中的json-simple库的新手,我已经通过了encoding和decoding样本。复制编码的例子很好,但我一直无法得到解码与混合类型JSON的工作。在Java中解码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的最简单方法是什么?
我们可以看到您的代码用于解码stat吗? –
您是否在[JSON官方解码教程](https://code.google.com/p/json-simple/wiki/DecodingExamples)中检查了示例5(可停止类SAX的内容处理程序) 正如我所见,该代码旨在用于单个字典(Map)/ Array。但是你正在尝试使用地图中的json(多个地图)。如果我错了,纠正我。 – ram2013
@ ram2013:你..我需要解码的是地图中的地图...我想这是其中之一。就好像我获得“stat”的值一样,我可以将它用于进一步的JSON解码。 –