简体   繁体   English

带有嵌套对象的 Json 字符串映射<String,String>

[英]Json string with nested objects to Map<String,String>

I have a json string with possible nested object inside like this:我有一个 json 字符串,里面可能有嵌套对象,如下所示:

{
    "stringTypeCode": "aaaaa",
    "choiceTypeCode1": {
        "option1": true,
        "option2": true
    },
    "choiceTypeCode2": {
        "option3": true,
        "option4": true
    }
}

I need it to convert to a Map leaving the nested objects as strings:我需要将其转换为 Map ,将嵌套对象保留为字符串:

stringTypeCode - aaaaa
choiceTypeCode1 - {"option1": true,"option2": true}
choiceTypeCode2 - {"option2": true,"option3": true}

Can it be done in a simple way, preferably without any library?能否以简单的方式完成,最好没有任何库?

Edit: or with a library if there is no other simple way.编辑:或者如果没有其他简单的方法,则使用库。

Edit2: I have a variable number of properties with variable names in the objects. Edit2:我在对象中有可变数量的属性和变量名。

Parse the json to a map or generic json structure, iterate over the key - value pairs, then create a new map from key - toJsonString(value) pairs.将 json 解析为映射或通用 json 结构,迭代key - value对,然后从key - toJsonString(value)对创建新映射。 value might be a simple string, json object, number etc... value可能是一个简单的字符串、json 对象、数字等...

With a simple Jackson ObjectMapper:使用简单的 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()));

Your example produces:你的例子产生:

stringTypeCode - "aaaaa"
choiceTypeCode1 - {"option1":true,"option2":true}
choiceTypeCode2 - {"option3":true,"option4":true}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM