【发布时间】:2020-07-13 11:33:25
【问题描述】:
如何定义我想要使用 jackson 反序列化 JSON 对象的映射键?
我的结构是这样的:
Class01:
public class Class01{
private String id;
private Map<String, Class02> entries;
}
Class02:
public class Class02{
private String name;
private String otherStuff;
}
我希望 Jackson 使用名称字符串作为映射对象的键。
JSON 看起来像这样:
{
"id": "1",
"entries": [
{
"name": "1",
"otherStuff": "asdf"
},
{
"name": "2",
"otherStuff": "ghkj"
},
{
"name": "3",
"otherStuff": "klyx"
}]
}
我使用这段代码从 json 文件中读取:
List<Class01> classes01 = objectMapper.readValue(jsonText, new TypeReference<List<Class01>>(){});
我已经尝试将@JsonDeserialize(using = HashMapValueDeserializer.class) 添加到地图中
我的反序列化方法如下所示:
@Override
public Map<String, Class02> deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
Map<String, Class02> ret = new HashMap<>();
ObjectCodec codec = parser.getCodec();
TreeNode classes02 = codec.readTree(parser);
String name, otherStuff;
if (classes02.isArray()) {
for (JsonNode class02: (ArrayNode) classes02) {
name = class02.get("name").asText();
if(class02.get("otherStuff")!=null) otherStuff = platformModule.get("otherStuff").asText();
else otherStuff = null;
ret.put(name, new Class02(name, otherStuff));
}
}
return ret;
}
【问题讨论】:
-
你能显示你想要反序列化的json吗?
-
请分享一些工作代码,显示您所做的努力以及可以纠正的问题
-
向我们展示您当前如何将 json 反序列化为 Java 类