Java 使用 Jackson 将 Json 嵌套到 Map

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19840818/
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-12 20:37:10  来源:igfitidea点击:

Nested Json to Map using Hymanson

javajsondictionary

提问by user2229544

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

我正在尝试将一些 JSON 动态解析为 Map。以下适用于简单的 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);

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

但是当我尝试使用一些带有嵌套信息的更复杂的 JSON 时失败了。我正在尝试解析来自 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"
        }
      }
    }
  }
}

I get the following error

我收到以下错误

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

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

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

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

回答by JamesB

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

我认为发生错误是因为 Hymanson 遇到 { 字符的那一刻,它将剩余内容视为新对象,而不是字符串。尝试将对象作为映射值而不是字符串。

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

output

输出

{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}}}}}

回答by Guido Medina

Wrap your Map into a dumb object as container, like this:

将您的 Map 包装成一个哑对象作为容器,如下所示:

public class Country {
  private final Map<String,Map<String,Set<String>>> citiesAndCounties=new HashMap<>;

  // Generate getters and setters and see the magic happen.
}

The rest is just working with your Object mapper, example Object mapper using Joda module:

其余的只是使用您的对象映射器,使用 Joda 模块的示例对象映射器:

public static final ObjectMapper JSON_MAPPER=new ObjectMapper().
          disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).
          setSerializationInclusion(JsonInclude.Include.NON_NULL).
          disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).
          registerModule(new JodaModule());

// Calling your Object mapper
JSON_MAPPER.writeValueAsString(new Country());

Hope that helps ;-)

希望有帮助;-)