用Java解码JSON字符串

Sha*_*ngh 17 java json json-simple

我是Java中使用json-simple库的新手,我已经完成了编码解码示例.复制编码示例很好,但是我无法使用混合类型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);
}
Run Code Online (Sandbox Code Playgroud)

json简单的官方解码教程,我试图解码这个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}
    ]
}
}
Run Code Online (Sandbox Code Playgroud)

我正在编写以下代码来解码:

    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);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.事实上,我无法使未经修改的示例工作,并且原作者没有解释他们的代码.

如图所示解码此JSON的最简单方法是什么?

Vee*_*tav 23

这是最好,最简单的代码:

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

这里给出了json文件库定义.它与此处发布的库不同,即由您发布.你发布的是我使用过这个库的简单json .

你可以下载zip.然后package使用org.json作为名称在项目中创建一个.并将所有下载的代码粘贴在那里,玩得开心.

我觉得这是最好和最简单的JSON解码.