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

孤街醉人 提交于 2021-02-07 20:12:44

问题


I have some class in Java that I want to convert to a Map<String, String>. The catch is that any fields of my java class that don't have an obvious String representation (collections, other classes) should be converted to json strings.

Here's an example:

@Data
@AllArgsConstructor
class MyClass {
    String field1;
    Long field2;
    Set<String> field3;
    OtherClass field4;
}

@Data
@AllArgsConstructor
class OtherClass {
    String field1;
    String field2;
}

ObjectMapper mapper = new ObjectMapper();
MyClass myClass = new MyClass("value", 
                              123L, 
                              Sets.newHashSet("item1", "item2"),
                              new OtherClass("value1", "value2"));
Map<String, String> converted =
        mapper.convertValue(myClass, new TypeReference<Map<String, String>>(){});

At this point, converted should look like the following:

"field1" -> "value"
"field2" -> "123"
"field3" -> "[\"item1\", \"item2\"]"
"field4" -> "{\"field1\":\"value1\",\"field2\":\"value2\"}"

Instead, the call to mapper.convertValue fails when trying to deserizlize the Set with the exception java.lang.IllegalArgumentException: Can not deserialize instance of java.lang.String out of START_ARRAY token.

Are there any special configurations I can annotate MyClass with or ways to configure the ObjectMapper to make this work the way I want it to?


回答1:


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


来源:https://stackoverflow.com/questions/33132827/how-to-convert-java-class-to-mapstring-string-and-convert-non-string-members

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!