gpt4 book ai didi

java - @JsonProperty 没有申请 BeanWrapper

转载 作者:太空宇宙 更新时间:2023-11-04 12:46:05 24 4
gpt4 key购买 nike

在创建流程中,ObjectMapper 转换工作正常(如果传递“first_name”和“last_name”)。我正在研究更新流程。我只需将有效负载数据修补到现有的数据库数据。

我的 POJO:

public class Contact
{
@JsonProperty( "first_name" )
@JsonView( ContactViews.CommonFields.class )
private String firstName;

@JsonProperty( "last_name" )
@JsonView( ContactViews.CommonFields.class )
private String lastName;

public String getFirstName()
{
return firstName;
}

public void setFirstName( String firstName )
{
this.firstName = firstName;
}

public String getLastName()
{
return lastName;
}

public void setLastName( String lastName )
{
this.lastName = lastName;
}
}

假设我现有的联系人只有“first_name”。我需要用“last_name”更新它。我收到 map 形式的有效负载( {"last_name":"XYZ"} )。如何使用有效负载 map 更新现有联系人。

现有的创建代码:

 Contact contact = mapper.readerWithView( ContactViews.CommonFields.class ).forType( Contact.class ).readValue( mapper.writeValueAsString( payloadMap ) );

我尝试添加额外的 getter 和 setter。一切正常。但我想克服这个问题,因为有很多领域。任何帮助将不胜感激!!

额外的 getter 和 setter (使其工作 - 但我需要避免它):

    @JsonProperty( "first_name" )
public String getFirst_name()
{
return firstName;
}

@JsonProperty( "first_name" )
public void setFirst_name( String firstName )
{
this.firstName = firstName;
}

@JsonProperty( "last_name" )
public String getLast_name()
{
return lastName;
}

@JsonProperty( "last_name" )
public void setLast_name( String lastName )
{
this.lastName = lastName;
}

我将其用于其他功能(但是如果没有额外的 getter 和 setter,这将无法工作):

public static void applyMapOntoInstance( Object instance , Map <String , ?> properties )
{
if ( Utilities.isEmpty( properties ) )
return;

String propertyName;

BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess( instance );
for ( Object name : properties.entrySet() )
{
Map.Entry <String , ?> entry = (Map.Entry <String , ?>) name;
propertyName = entry.getKey();
if ( beanWrapper.isWritableProperty( propertyName ) )
beanWrapper.setPropertyValue( propertyName , entry.getValue() );
}
}

public static void copyValues( Object source , Object target , Iterable <String> properties )
{
BeanWrapper src = new BeanWrapperImpl( source );
BeanWrapper trg = new BeanWrapperImpl( target );

for ( String propertyName : properties )
trg.setPropertyValue( propertyName , src.getPropertyValue( propertyName ) );
}

最佳答案

使用com.fasterxml.jackson.annotation.JsonProperty

关于java - @JsonProperty 没有申请 BeanWrapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36308248/

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