gpt4 book ai didi

java - 如何对用于不同服务的域对象使用 JACKSON 序列化程序?

转载 作者:行者123 更新时间:2023-11-29 09:10:39 25 4
gpt4 key购买 nike

我有一个域对象用于以下两种不同的服务:

public class PersonDetails {

private String personId;
private String personMaritalStatus;
private String personFirstName;
private String personLastName;

// setters and getters ...
}

并且有两种不同的服务。

第一个:

public BaseResponse getClient(@QueryParam("id") @DefaultValue("-1") String id) 
{
}

此服务应返回如下 json:

{ "personId":12, 
"personMaritalStatus":"married",
"personFirstname" :"abc",
"personLastname":"pqr" }

第二个服务:

public BaseResponse getClientName(@QueryParam("id") @DefaultValue("-1") String id) 
{
}

此服务应返回如下 json:

{"personFirstname" :"abc"}

因此,如果我在域对象上使用 @JsonSerialize(using=PersonDetailsS​​erializer.class),序列化器类将如下所示:

public class PersonDetailsSerializerextends JsonSerializer<PersonDetails> 
{
@Override
public void serialize(PersonDetails personDetails,
JsonGenerator jsonGenerator,
SerializerProvider serializerProvider)
throws IOException, JsonProcessingException {
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("personFirstname", personDetails.getpersonFirstName());
jsonGenerator.writeEndObject();
}
}

然后它也会影响 getPerson 服务的响应。

那么我如何使用服务级别序列化或使用 JACKSON 的任何其他方式来处理这个问题......

最佳答案

您可以使用两种不同的 ObjectMappers,一种带有 MixIn,另一种不带。

abstract class PersonNameMixIn {
@JsonIgnore()
abstract String getPersonLastName();
@JsonIgnore()
abstract String getPersonMaritalStatus();
}

public getClientName() {
ObjectMapper mapper = new ObjectMapper();
mapper.getSerializationConfig().addMixInAnnotations(PersonDetails.class, PersonNameMixIn.class);
mapper.writeValue(writer, person);
}

public getClient() {
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(writer, person);
}

关于java - 如何对用于不同服务的域对象使用 JACKSON 序列化程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12616730/

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