首页 > 解决方案 > 将包含数组的json字符串转换为Java中的Map

问题描述

我需要在 Java 中为以下 json 字符串将 String 转换为 Map:请注意,这个 json 字符串中有数组,这就是我面临的问题:

{
   "type":"auth",
   "amount":"16846",
   "level3":{
      "amount":"0.00",
      "zip":"37209",
      "items":[
         {
            "description":"temp1",
            "commodity_code":"1",
            "product_code":"11"
         },
         {
            "description":"temp2",
            "commodity_code":"2",
            "product_code":"22"
         }
      ]
   }
}

我尝试了以下链接中提到的几种方法:

将 JSON 字符串转换为 Map – Jackson

解析 JSONObject 并创建 HashMap

我得到的错误:

JSON 解析器错误:无法从 START_OBJECT 令牌中反序列化 java.lang.String 的实例 ... }; 行:3,列:20](通过引用链:java.util.LinkedHashMap["level3"])com.fasterxml.jackson.databind.JsonMappingException:无法从 START_OBJECT 令牌中反序列化 java.lang.String 的实例

因此,为了提供有关我正在使用 Map 的更多详细信息,此地图将使用以下方法转换回 json 字符串:

    public static String getJSON(Object map) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    OutputStream stream = new BufferedOutputStream(byteStream);
    JsonGenerator jsonGenerator = objectMapper.getFactory().createGenerator(stream, JsonEncoding.UTF8);
    objectMapper.writeValue(jsonGenerator, map);
    stream.flush();
    jsonGenerator.close();
    return new String(byteStream.toByteArray());
}

标签: javaarraysjsonjackson

解决方案


您无法将 JSON 内容解析为 a Map<String, String> (就像在您发布的两个链接中所做的那样)。但是您可以将其解析为Map<String, Object>.

例如像这样:

ObjectMapper mapper = new ObjectMapper();
File file = new File("example.json");
Map<String, Object> map;
map = mapper.readValue(file, new TypeReference<Map<String, Object>>(){});

推荐阅读