简体   繁体   English

在 Java 中解码 JSON 字符串

[英]Decoding JSON String in Java

I am new to using the json-simple library in Java and I've been through both the encoding and decoding samples.我是在 Java 中使用 json-simple 库的新手,我已经完成了编码解码示例。 Duplicating the encoding examples was fine, but I have not been able to get the decoding ones to work with mixed type JSON.复制编码示例很好,但我无法让解码示例与混合类型的 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 的最简单方法是什么?

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 .此处给出了 json 文件库定义 And it is not same libraries as posted here , ie posted by you.它与此处发布的库不同,即您发布的库。 What you had posted was simple json library I have used this library .您发布的是简单的 json 库,我使用过这个库

You can download the zip .您可以下载 zip 文件 And then create a package in your project with org.json as name.然后创建一个packageorg.json姓名您的项目。 and paste all the downloaded codes there, and have fun.并将所有下载的代码粘贴到那里,玩得开心。

I feel this to be the best and the most easiest JSON Decoding.我觉得这是最好和最简单的 JSON 解码。

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 jsonString and if you use the same JSONParser and ContainerFactory in the example you will see that it will be encoded/decoded.使用这个jsonString并且如果您在示例中使用相同的JSONParserContainerFactory ,您将看到它将被编码/解码。

Additionally if you want to print your string after stat here 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.关于 json 库,有很多。 Better you check this .最好检查一下

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

Instead of downloading separate java files as suggested by Veer, you could just add this JAR file to 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转到库选项卡 > 添加外部 JAR
  3. Locate the JAR file and add找到 JAR 文件并添加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM