gpt4 book ai didi

java - @jsonview 在未知属性上失败

转载 作者:行者123 更新时间:2023-11-30 10:47:05 25 4
gpt4 key购买 nike

我需要使用@JsonView 在反序列化时抛出异常。

我的 POJO:

public class Contact
{
@JsonView( ContactViews.Person.class )
private String personName;

@JsonView( ContactViews.Company.class )
private String companyName;
}

我的服务:

public static Contact createPerson(String json) {

ObjectMapper mapper = new ObjectMapper().configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , true );

Contact person = mapper.readerWithView( ContactViews.Person.class ).forType( Contact.class ).readValue( json );

return person;
}


public static Contact createCompany(String json) {

ObjectMapper mapper = new ObjectMapper().configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , true );

Contact company = mapper.readerWithView( ContactViews.Company.class ).forType( Contact.class ).readValue( json );

return company;
}

我需要实现的是,如果我尝试创建一个人,我只需要传递“personName”。如果我传递“companyName”,我需要抛出异常。我如何使用@JsonView 实现这一目标?有其他选择吗?

最佳答案

我认为 @JsonView 不足以为您解决这个问题。以下是更多信息:UnrecognizedPropertyException is not thrown when deserializing properties that are not part of the view

但我只是查看了源代码并设法通过组合使用 @JsonView 和自定义 BeanDeserializerModifier 来“解决”这个问题。它不漂亮,但这是必不可少的部分:

public static class MyBeanDeserializerModifier extends BeanDeserializerModifier {

@Override
public BeanDeserializerBuilder updateBuilder(DeserializationConfig config,
BeanDescription beanDesc, BeanDeserializerBuilder builder) {
if (beanDesc.getBeanClass() != Contact.class) {
return builder;
}

List<PropertyName> properties = new ArrayList<>();
Iterator<SettableBeanProperty> beanPropertyIterator = builder.getProperties();
Class<?> activeView = config.getActiveView();


while (beanPropertyIterator.hasNext()) {
SettableBeanProperty settableBeanProperty = beanPropertyIterator.next();
if (!settableBeanProperty.visibleInView(activeView)) {
properties.add(settableBeanProperty.getFullName());
}
}

for(PropertyName p : properties){
builder.removeProperty(p);
}

return builder;
}
}

下面是如何在对象映射器上注册它:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new MyBeanDeserializerModifier());
mapper.registerModule(module);

这对我有用,我现在得到 UnrecognizedPropertyException:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "companyName" (class Main2$Contact), not marked as ignorable (one known property: "personName"])

关于java - @jsonview 在未知属性上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36263244/

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