gpt4 book ai didi

java - 如何将 Java 类转换为 Map 并使用 jackson 将非字符串成员转换为 json?

转载 作者:行者123 更新时间:2023-12-03 19:25:30 25 4
gpt4 key购买 nike

我有一些 Java 类,我想将其转换为 Map<String, String> .问题是我的 java 类的任何字段都没有明显的 String表示(集合、其他类)应转换为 json 字符串。

这是一个例子:

@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>>(){});

此时, converted应如下所示:
"field1" -> "value"
"field2" -> "123"
"field3" -> "[\"item1\", \"item2\"]"
"field4" -> "{\"field1\":\"value1\",\"field2\":\"value2\"}"

相反,调用 mapper.convertValue尝试反序列化 Set 时失败,出现异常 java.lang.IllegalArgumentException: Can not deserialize instance of java.lang.String out of START_ARRAY token .

有什么特殊的配置可以注释 MyClass使用或配置 ObjectMapper的方法使这项工作按我想要的方式工作?

最佳答案

这是一种方法。

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

如果您想将 Map 转换回原始类...
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;
}

关于java - 如何将 Java 类转换为 Map<String, String> 并使用 jackson 将非字符串成员转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com