gpt4 book ai didi

java - 仅对某些类使用 Json 根元素

转载 作者:搜寻专家 更新时间:2023-11-01 00:55:55 26 4
gpt4 key购买 nike

我正在使用 dropwizard 创建 REST API。但我不明白,如何配置 Jackson 以从 WRAP_ROOT_VALUE/UNWRAP_ROOT_VALUE 功能中排除某些类?现在我收到一个不包含根元素名称的 json 正文的发布请求:

{
"identification": "dummyuser",
"password":"dummypass"
}

这应该映射到 java 类 LoginRequest:

public class LoginRequest {
public String identidication;
public String passwrd;
}

我还收到一些包含根元素名称的类型的请求:

{
"user":{
"id":12345,
"name":"John Doe"
}
}

这应该映射到:

@JsonRootName("user")
public class User {
...
}

要使根元素正常工作,我必须包括:

    environment.getObjectMapper().configure(SerializationFeature.WRAP_ROOT_VALUE, true);
environment.getObjectMapper().configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

但现在它适用于所有类。这意味着每当登录请求到来时,服务器都会抛出错误,因为它希望看到根元素名称。

最佳答案

使用 JsonTypeNameJsonTypeInfo 而不是 JsonRootName:

@JsonTypeName("user")
@JsonTypeInfo(include= JsonTypeInfo.As.WRAPPER_OBJECT,use= JsonTypeInfo.Id.NAME)
public class User {
...
}

@JsonTypeName

Annotation used for binding logical name that the annotated class has. Used with JsonTypeInfo (and specifically its JsonTypeInfo.use() property) to establish relationship between type names and types.

@JsonTypeInfo

Annotation used for configuring details of if and how type information is used with JSON serialization and deserialization, to preserve information about actual class of Object instances. This is necessarily for polymorphic types, and may also be needed to link abstract declared types and matching concrete implementation.

关于java - 仅对某些类使用 Json 根元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30288503/

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