在 Java 中解码 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16574482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:31:04  来源:igfitidea点击:

Decoding JSON String in Java

javajsonjson-simple

提问by Sharda Singh

I am new to using the json-simple library in Java and I've been through both the encodingand decodingsamples. Duplicating the encoding examples was fine, but I have not been able to get the decoding ones to work with mixed type JSON.

我是在 Java 中使用 json-simple 库的新手,我已经完成了编码解码示例。复制编码示例很好,但我无法让解码示例与混合类型的 JSON 一起使用。

One of my problems is that there are too many classes in the library which are not properly documented, and for which I do not have the source (in order to be able to read through and understand their purpose). Consequently, I am struggling to understand how to use a lot of these classes.

我的问题之一是库中有太多类没有正确记录,并且我没有源代码(为了能够通读并理解它们的目的)。因此,我很难理解如何使用这些类中的很多。

After reading this example:

阅读此示例后:

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);
}

from the json-simple official decoding tutorial, I tried to decode this JSON:

json-simple官方解码教程中,我尝试解码这个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}
    ]
}
}

I am writing following code to decode:

我正在编写以下代码进行解码:

    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);

But it doesn't work. Infact I was not able to get the unmodified example working either, and the original authors have not explained their code.

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

What is the easiest way to decode this JSON as shown?

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

采纳答案by Veer Shrivastav

This is the best and easiest code:

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

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"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json libraryI have used this library.

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

You can download the zip. And then create a packagein your project with org.jsonas name. and paste all the downloaded codes there, and have fun.

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

I feel this to be the best and the most easiest JSON Decoding.

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

回答by anvarik

Well your jsonString is wrong.

那么你的 jsonString 是错误的。

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}]}}";

use this jsonStringand if you use the same JSONParserand ContainerFactoryin the example you will see that it will be encoded/decoded.

使用它jsonString,如果您使用相同的,JSONParser并且ContainerFactory在示例中,您将看到它将被编码/解码。

Additionally if you want to print your string after stathere it goes:

此外,如果您想在stat此处打印字符串,请执行以下操作:

     try{
        Map json = (Map)parser.parse(jsonString, containerFactory);
        Iterator iter = json.entrySet().iterator();
        System.out.println("==iterate result==");
        Object entry = json.get("stat");
        System.out.println(entry);
      }

And about the json libraries, there are a lot of them. Better you check this.

关于 json 库,有很多。最好检查一下

回答by alphayax

This is the JSON String we want to decode :

这是我们要解码的 JSON 字符串:

{ 
   "stats": { 
       "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}
       ]}
}

I store this string under the variable name "sJSON" Now, this is how to decode it :)

我将此字符串存储在变量名称“sJSON”下 现在,这是解码它的方法:)

// Creating a JSONObject from a String 
JSONObject nodeRoot  = new JSONObject(sJSON); 

// Creating a sub-JSONObject from another JSONObject
JSONObject nodeStats = nodeRoot.getJSONObject("stats");

// Getting the value of a attribute in a JSONObject
String sSDR = nodeStats.getString("sdr");

回答by Afreen

Instead of downloading separate java files as suggested by Veer, you could just add this JAR fileto your package.

无需像 Veer 建议的那样下载单独的 java 文件,您只需将此JAR 文件添加到您的包中即可。

To add the jar file to your project in Eclipse, do the following:

要将 jar 文件添加到 Eclipse 中的项目,请执行以下操作:

  1. Right click on your project, click Build Path > Configure Build Path
  2. Goto Libraries tab > Add External JARs
  3. Locate the JAR file and add
  1. 右键单击您的项目,单击构建路径 > 配置构建路径
  2. 转到库选项卡 > 添加外部 JAR
  3. 找到 JAR 文件并添加