Home > Mobile >  How to convert JSONObject to Map in Java
How to convert JSONObject to Map in Java

Time:04-22

I get a JSONObject from the client and I want to convert it to a Map in Java Spring-Boot. Does anyone know a good approach with my data structure?

Json Object:

FilterObject: {
               "firstName":
                 {"filterType":"text","type":"contains","filter":"emma"},...
               }

Map to:

Map<String, ColumnFilter> filterMap;
public class ColumnFilter {
    private String filterType;
    private String type;
    private String filter;
}

CodePudding user response:

You can use this code snippet:

String columnFilterJson = "{\"firstName\":{\"filterType\":\"text\",\"type\":\"contains\",\"filter\":\"emma\"}}";
ObjectMapper objectMapper = new ObjectMapper();
HashMap<String, ColumnFilter> columnFilterMap = objectMapper.readValue(columnFilterJson, new TypeReference<HashMap<String, ColumnFilter>>() {});

Then with considering your ColumnFilter class has toString() method you can check result:

for (Map.Entry<String, ColumnFilter> entry: columnFilterMap.entrySet()) {
    String key = entry.getKey();
    ColumnFilter value = entry.getValue();
    System.out.println(key);
    System.out.println(value);
}
  • Related