首页 > 解决方案 > 带有嵌套对象的 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:我在对象中有可变数量的带有变量名称的属性。

标签: javajson

解决方案


将 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}

推荐阅读