gpt4 book ai didi

java - JaxRS 和 Jackson 的多态性

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

我有类 Admin 扩展了 User {}AdminUser 都扩展了 @XmlRootElement

@XmlRootElement
public class User {
....
}

@XmlRootElement
public class Admin extends User {

String statement;
}

我将此 Json 发送到正确的 JaxRS 服务:

{
"id": "84",
"content": "blablah",
"user": {
"id": 1,
"email": "nicolas@robusta.io",
"name": "Nicolas",
"male": true,
"admin": true,
"statement":"hello world"
}
}

这是 Web 服务。该评论应该有一个User,但我们这里有一个管理员,它有一个statement字段,对于User来说是未知的。

@POST
@Path("{id}/comments")
public Response createComment(@PathParam("id") long topicId, Comment comment) { ... }

jackson 不接受评论作为评论,因为它的用户管理员:

@XmlRootElement
public class Comment {
String id;
String content;
User user = null;
}

我应该如何告诉 jackson 接受任何类型的用户?如何做到最兼容 Java EE(即具有另一个 Json 处理程序的服务器)?

最佳答案

jackson 使用多态对象的方法是在 json 中添加一些附加字段并使用 @JsonTypeInfo 如果您可以将 json 更改为类似的内容

"user": {
"type": "Admin",
...
}

然后你可以简单地使用

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(name = "User", value = User.class),
@JsonSubTypes.Type(name = "Admin", value = Admin.class)
})
static class User {
public String id;
}
<小时/>

如果您无法更改 json,那么事情可能会变得复杂,因为没有默认方法来处理这种情况,您将不得不编写自定义反序列化器。基本的简单情况看起来像这样:

public static class PolymorphicDeserializer extends JsonDeserializer<User> {
ObjectMapper mapper = new ObjectMapper();

@Override
public User deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode tree = p.readValueAsTree();

if (tree.has("statement")) // <= hardcoded field name that Admin has
return mapper.convertValue(tree, Admin.class);

return mapper.convertValue(tree, User.class);

}
}

您可以在ObjectMapper上注册它

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(User.class, new PolymorphicDeserializer());
mapper.registerModule(module);

或带注释:

@JsonDeserialize(using = PolymorphicDeserializer.class)
class User {
public String id;
}

关于java - JaxRS 和 Jackson 的多态性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47098033/

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