【问题标题】:Convert json String containing array to Map in Java将包含数组的json字符串转换为Java中的Map
【发布时间】:2019-01-27 23:01:52
【问题描述】:

我需要在 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"
         }
      ]
   }
}

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

Convert JSON string to Map – Jackson

Parse the JSONObject and create HashMap

我得到的错误:

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

所以要详细说明我正在使用地图做什么,这个地图将使用以下方法转换回 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());
}

【问题讨论】:

  • 面临什么问题?你试过什么?怎么没用?如果您 edit 您的问题包含您的尝试,那么找出您卡在哪里会容易得多。
  • 添加了详细信息,基本上我想知道我尝试这样做的方式是否也会处理 json 字符串中的 Array?
  • map 适用于来自 json 的键值对,但您有复杂的数据结构。你必须从 json 中提取哪些元素?
  • 了解您期望地图的外观也很有用。例如,“level3”对象应该发生什么。
  • 您不应该为此使用地图。创建适当的类结构并使用像 Jackson 这样的库来反序列化您的 JSON。

标签: java arrays json jackson


【解决方案1】:

您无法将 JSON 内容解析为 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>>(){});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    相关资源
    最近更新 更多