java - 将包含数组的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 解析器错误:无法从 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());
}
解决方案
您无法将 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>>(){});
推荐阅读
- python - 如何拆分熊猫列并检查值?
- c++ - c++如何读取windows10安全事件一般信息?
- android - 如何在kotlin中对队列的所有元素求和?
- python - 如何识别这个 div 标签?
- excel - 从所有工作表中提取一些数据并复制到另一张工作表中
- c++ - ZMQ REP 如何释放 CPU 时间
- laravel - 一次性将信息存储到 order 和 order_details 表中
- java - 依赖项没有从导入的 jar 文件反映到我的 Spring Boot 项目中
- android - 预期为 BEGIN_OBJECT,但在路径 $[0] 处是字符串
- kubernetes - Kubernetes 容器运行时网络未准备好