使用Jackson嵌套Json到Map

时间:2013-11-07 16:08:15

标签: java json dictionary

我正在尝试动态地将一些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"
        }
      }
    }
  }
}

我收到以下错误

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

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

2 个答案:

答案 0 :(得分:12)

我认为错误的发生是因为杰克逊遇到{字符时,它将剩余内容视为新对象,而不是字符串。尝试使用Object作为映射值而不是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}}}}}

答案 1 :(得分:1)

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

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

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

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

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

希望有所帮助; - )