[英]Jackson deserialize json array into single property of one class
I have a json array: 我有一个json数组:
[
//...
{"name": "admin", id: 1},
//...
]
and two classes named Team, Profile: 还有两个名为Team,Profile的类:
class Team {
Profile profile;
}
class Profile {
String name;
long id;
}
so, is it possible to deserialise the json to a list of Team, but the json properties are mapped to the profile property of class Team? 因此,是否可以将json反序列化为Team列表,但是json属性映射到Team类的profile属性?
Thank u very much. 十分感谢。
Yes, you can do it by writing your custom deserializer like this: 是的,您可以这样编写您的自定义解串器来实现:
public class TeamDeserializer extends JsonDeserializer<Team> {
@Override
public Team deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
//read the node and set fields
String name = node.get("name").asText();
int id = (Integer) ((IntNode) node.get("id")).numberValue();
//returning in required format
return new Team(new Profile(name, id));
}
}
You have to register this deserializer before using it like this: 您必须先注册该反序列化器,然后才能使用它,如下所示:
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Team.class, new TeamDeserializer());
mapper.registerModule(module);
Team value = mapper.readValue(json, Team.class);
You can modify this for list. 您可以修改此列表。
HTH! HTH!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.