9

我正在尝试将一些 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);

但是当我尝试使用一些更复杂的带有嵌套信息的 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"
        }
      }
    }
  }
}

我收到以下错误

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

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

4

2 回答 2

16

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

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}}}}}
于 2013-11-07T16:33:45.413 回答
1

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

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

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

其余的只是使用您的对象映射器,例如使用 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());

希望有帮助;-)

于 2013-11-07T16:41:29.583 回答