[英]Convert nested JSON to nested HashMap
How can we convert the nested json to nested hashmap without creating the pojo classes.我们如何在不创建 pojo 类的情况下将嵌套的 json 转换为嵌套的 hashmap。
{
"IdeskFields": [
{
"fieldName": "CLIENT_TAX_TYPE_ID",
"values": [
{
"key": "dataType",
"value": "Integer"
},
{
"key": "CLIENT_TAX_TYPE_VAT",
"value": "2"
},
{
"key": "CLIENT_TAX_TYPE_GST",
"value": "8"
},
{
"key": "CLIENT_TAX_TYPE_Tax",
"value": "9"
}
]
}
]
}
Need to be converted to Map<String, Map<String, String>> map需要转换为 Map<String, Map<String, String>> map
You can use ObjectMapper
from jackson
.您可以使用jackson
中的ObjectMapper
。
Map map = new ObjectMapper().readValue(jsonString, HashMap.class);
A map will be an instance of map 将是
HashMap<String, ArrayList<LinkedHashMap<String, ArrayList<LinkedHashMap<String, String>>>>>
If you can use the Gson
library then you can do something like this如果您可以使用Gson
库,那么您可以执行以下操作
Gson gson = new Gson();
Map map = gson.fromJson(str, Map.class);
But that would leave to the library to determine the type of values.但这将留给图书馆来确定值的类型。
Therefore better way to use Gson#fromJson(String, Type)
something like below:因此使用Gson#fromJson(String, Type)
的更好方法如下:
Type mapType = new TypeToken<Map<String, List<Map<String, Object>>>>() {}.getType();
Map<String, List<Map<String, Object>>> map = gson.fromJson(str, mapType);
I use Object as inner map value type because your values are different ie string and list of another map.我使用 Object 作为内部 map 值类型,因为您的值不同,即字符串和另一个 map 的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.