gpt4 book ai didi

java - 如何将两个相同的 json 属性名称分配给两个单独的字段

转载 作者:行者123 更新时间:2023-12-04 03:56:10 24 4
gpt4 key购买 nike

我有以下 Java 类 enter image description here

我需要通过以下方式将其序列化为json:

如果列表(paymentTransactionReport 字段)不为空,则显示它的值 -

{ 
"paymentTransactionResponse" : [
{},
{}
]
}

如果列表为空,我需要在名称为“paymentTransactionResponse”的 json 字段中显示 paymentTransactionReportError,就像之前的情况一样。示例 -

{
"paymentTransactionResponse" : {
----
//fields from PaymentTransactionReportError class
----
}
}

我该怎么做?最好不要自定义序列化器。如果像我一样只使用两个同名的注释@JsonProperty 和 JsonInclude.NON_NULL,我会遇到这个错误:No converter found for return value of type:... Seems to be that is a error happened during serialization because of fields with同名

最佳答案

实现此目的的一种方法是使用 @JsonAnyGetter , 试试这个

public class TestDTO {

@JsonIgnore
List<String> paymentTransactionResponse;

@JsonIgnore
String paymentTransactionResponseError;

public List<String> getPaymentTransactionResponse() {
return paymentTransactionResponse;
}

public void setPaymentTransactionResponse(List<String> paymentTransactionResponse) {
this.paymentTransactionResponse = paymentTransactionResponse;
}

public String getPaymentTransactionResponseError() {
return paymentTransactionResponseError;
}

public void setPaymentTransactionResponseError(String paymentTransactionResponseError) {
this.paymentTransactionResponseError = paymentTransactionResponseError;
}

@JsonAnyGetter
public Map<String, Object> getData(){
Map<String, Object> map = new HashMap<String, Object>();
if(paymentTransactionResponse != null) {
map.put("paymentTransactionResponse", paymentTransactionResponse);
}else {
map.put("paymentTransactionResponse", paymentTransactionResponseError);
}
return map;
}}

关于java - 如何将两个相同的 json 属性名称分配给两个单独的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63882140/

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