Decoding JSON String in Java

感情迁移 提交于 2019-11-26 11:10:03

问题


I am new to using the json-simple library in Java and I\'ve been through both the encoding and decoding samples. Duplicating the encoding examples was fine, but I have not been able to get the decoding ones to work with mixed type 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:

{
\"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?


回答1:


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 library I have used this library.

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

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




回答2:


Well your jsonString is wrong.

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.

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

     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.




回答3:


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

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

  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



回答4:


This is the JSON String we want to decode :

{ 
   "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 :)

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


来源:https://stackoverflow.com/questions/16574482/decoding-json-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!