java - 带有嵌套对象的 Json 字符串映射
问题描述
我有一个带有可能嵌套对象的 json 字符串,如下所示:
{
"stringTypeCode": "aaaaa",
"choiceTypeCode1": {
"option1": true,
"option2": true
},
"choiceTypeCode2": {
"option3": true,
"option4": true
}
}
我需要将其转换为 Map 将嵌套对象保留为字符串:
stringTypeCode - aaaaa
choiceTypeCode1 - {"option1": true,"option2": true}
choiceTypeCode2 - {"option2": true,"option3": true}
可以以简单的方式完成,最好没有任何库吗?
编辑:如果没有其他简单的方法,或者使用图书馆。
Edit2:我在对象中有可变数量的带有变量名称的属性。
解决方案
将 json 解析为映射或通用 json 结构,遍历key - value
对,然后从对创建新映射key - toJsonString(value)
。value
可能是一个简单的字符串、json 对象、数字等...
使用简单的 Jackson ObjectMapper:
String json = "YOUR JSON HERE";
ObjectMapper mapper = new ObjectMapper();
Iterator<Entry<String, JsonNode>> fields = mapper.readTree(json).fields();
Map<String, String> m = new HashMap<>();
while (fields.hasNext()) {
Entry<String, JsonNode> field = fields.next();
m.put(field.getKey(), mapper.writeValueAsString(field.getValue()));
}
m.entrySet().forEach(e -> System.out.println(e.getKey() + " - " + e.getValue()));
您的示例产生:
stringTypeCode - "aaaaa"
choiceTypeCode1 - {"option1":true,"option2":true}
choiceTypeCode2 - {"option3":true,"option4":true}
推荐阅读
- linux - 用我自己的 .config 文件编译上游内核
- dart - Intellij IDEA 自定义飞镖格式。如何在同一行上制作点运算符
- string - 如何添加到列表中的字符串?(从亚马逊上刮掉链接)
- bash - 如何使用 plutil 将数据替换为 .plist 文件
- json - 如何禁用单击列表视图中的特定项目
- javascript - Vue - 如何使用一个插件两次但设置不同?
- reporting-services - SSRS 中的求和字段
- python-3.x - 如何一次声明重复的文件名和路径?
- python - 如何在 django db 中传递 if else 语句以在 django 中获取模型
- c - 将字符串转换为字符串,每个字母都转换为前一个字母