使用杰克逊的嵌套Json映射 [英] Nested Json to Map using Jackson

查看:250
本文介绍了使用杰克逊的嵌套Json映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动态解析一些JSON到地图。以下内容适用于简单的JSON

I'm trying to dynamically parse some JSON to a Map. The following works well with simple JSON

        String easyString = "{\"name\":\"mkyong\", \"age\":\"29\"}";
    Map<String,String> map = new HashMap<String,String>();
    ObjectMapper mapper = new ObjectMapper();

    map = mapper.readValue(easyString, 
            new TypeReference<HashMap<String,String>>(){});

    System.out.println(map);

但是当我尝试使用一些更复杂的JSON与嵌套信息时,失败。我试图从json.org解析样本数据

But fails when I try to use some more complex JSON with nested information. I'm trying to parse the sample data from json.org

{
  "glossary": {
    "title": "example glossary",
    "GlossDiv": {
      "title": "S",
      "GlossList": {
        "GlossEntry": {
          "ID": "SGML",
          "SortAs": "SGML",
          "GlossTerm": "Standard Generalized Markup Language",
          "Acronym": "SGML",
          "Abbrev": "ISO 8879:1986",
          "GlossDef": {
            "para": "A meta-markup language, used to create markup languages such as DocBook.",
            "GlossSeeAlso": [
              "GML",
              "XML"
            ]
          },
          "GlossSee": "markup"
        }
      }
    }
  }
}

我收到以下错误

线程main中的异常com.fasterxml.jackson.databind.JsonMappingException:无法反序列化java.lang.String的实例在START_OBJECT令牌中

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token

有没有办法将复杂的JSON数据解析成地图?

Is there a way to parse complex JSON data into a map?

推荐答案

我认为发生错误是因为Jackson遇到了{character,它将剩余内容视为新对象而不是字符串。尝试对象作为映射值而不是String。

I think the error occurs because the minute Jackson encounters the { character, it treats the remaining content as a new object, not a string. Try Object as map value instead of String.

public static void main(String[] args) throws IOException {

    Map<String,String> map = new HashMap<String,String>();
    ObjectMapper mapper = new ObjectMapper();

    map = mapper.readValue(x, new TypeReference<HashMap>(){});

    System.out.println(map);
}

输出

{glossary={title=example glossary, GlossDiv={title=S, GlossList={GlossEntry={ID=SGML, SortAs=SGML, GlossTerm=Standard Generalized Markup Language, Acronym=SGML, Abbrev=ISO 8879:1986, GlossDef={para=A meta-markup language, used to create markup languages such as DocBook., GlossSeeAlso=[GML, XML]}, GlossSee=markup}}}}}

这篇关于使用杰克逊的嵌套Json映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆