-4

I have a json string with possible nested object inside like this:

{
    "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:

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.

neptune
  • 1,211
  • 2
  • 19
  • 32

1 Answers1

3

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. value might be a simple string, json object, number etc...

With a simple 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}
David Szalai
  • 2,363
  • 28
  • 47