【问题标题】:Decoding JSON String in Java在 Java 中解码 JSON 字符串
【发布时间】:2013-05-10 13:57:46
【问题描述】:

我不熟悉在 Java 中使用 json-simple 库,并且我已经通过了 encodingdecoding 示例。复制编码示例很好,但我无法让解码示例与混合类型 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 的最简单方法是什么?

【问题讨论】:

  • 我们可以看看你的解码数据的代码吗?
  • 您是否检查过JSON official decoding tutorial 中的示例 5(可停止的 SAX 类内容处理程序)我可以看到该代码适用于单个字典(地图)/数组。但是您正在尝试使用地图中的地图(多个地图)的 json。如果我错了,请纠正我。
  • @ram2013:是的……我需要解码的是地图中的地图……我想这就是其中之一。好像我得到了“stat”的值,我可以用它来进一步解码 JSON。
  • 问我最简单的方法是什么?这个>>code.google.com/p/google-gson
  • 首先你的jsonString 不是一个有效的json。 argv 里面的那个东西是什么??

标签: java json json-simple


【解决方案1】:

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

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

library definition of the json files are given here。它与here 发布的库不同,即由您发布。你发的是simple json library我用过this library

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

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

【讨论】:

  • 我们如何在JSON 中添加转义` to "`?我不想做String.replace()
  • 我不断收到此输出“A JSONObject 文本必须在 1 [字符 2 第 1 行] 处以 '{' 开头”我的 JSON 内容在第二个“{”之前没有任何内容
  • org.json 是可用的最差解决方案之一。它的性能很糟糕,并且功能集不存在。这主要是因为它是在 json 的早期由它的创建者开发的,作为一个概念验证库。在选择之前考虑性能:github.com/fabienrenaud/java-json-benchmark(使用 JMH 完成)。杰克逊是你的赢家。
  • 第一个链接是 404
【解决方案2】:

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

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

另外,如果你想在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);
      }

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

【讨论】:

    【解决方案3】:

    您可以将 JAR file 添加到您的包中,而不是按照 Veer 的建议下载单独的 java 文件。

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

    1. 右击你的项目,点击构建路径>配置构建路径
    2. 转到库选项卡 > 添加外部 JAR
    3. 找到 JAR 文件并添加

    【讨论】:

      【解决方案4】:

      这是我们要解码的 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}
             ]}
      }
      

      我将此字符串存储在变量名称“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");
      

      【讨论】:

      • “stat”处缺少字母“s”,应为 JSONObject nodeStats = nodeRoot.getJSONObject("stats");对吗?
      • 看起来JSONObject 不再具有接受字符串的初始化程序。
      猜你喜欢
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多