How to convert Java class to Map<String, String> and convert non-string members to json using jackson? How to convert Java class to Map<String, String> and convert non-string members to json using jackson? json json

How to convert Java class to Map<String, String> and convert non-string members to json using jackson?


Here's one way to do it.

private static final ObjectMapper mapper = new ObjectMapper();public Map<String, String> toMap(Object obj) {    // Convert the object to an intermediate form (map of strings to JSON nodes)    Map<String, JsonNode> intermediateMap = mapper.convertValue(obj, new TypeReference<Map<String, JsonNode>>() {});    // Convert the json nodes to strings    Map<String, String> finalMap = new HashMap<>(intermediateMap.size() + 1); // Start out big enough to prevent resizing    for (Map.Entry<String, JsonNode> e : intermediateMap.entrySet()) {        String key = e.getKey();        JsonNode val = e.getValue();        // Get the text value of textual nodes, and convert non-textual nodes to JSON strings        String stringVal = val.isTextual() ? val.textValue() : val.toString();        finalMap.put(key, stringVal);    }    return finalMap;}

And if you want to convert the Map<String, String> back to the original class...

public static <T> T fromMap(Map<String, String> map, Class<T> clazz) throws IOException {    // Convert the data to a map of strings to JSON nodes    Map<String, JsonNode> intermediateMap = new HashMap<>(map.size() + 1); // Start out big enough to prevent resizing    for (Map.Entry<String, String> e : map.entrySet()) {        String key = e.getKey();        String val = e.getValue();        // Convert the value to the right type of JsonNode        JsonNode jsonVal;        if (val.startsWith("{") || val.startsWith("[") || "null".equals(val)) {            jsonVal = mapper.readValue(val, JsonNode.class);        } else {            jsonVal = mapper.convertValue(val, JsonNode.class);        }        intermediateMap.put(key, jsonVal);    }    // Convert the intermediate map to an object    T result = mapper.convertValue(intermediateMap, clazz);    return result;}