gpt4 book ai didi

java - 如果没有自定义序列化程序,是否可以对这个字符串进行 Jackson 序列化?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:37:20 25 4
gpt4 key购买 nike

我想序列化我作为 POJO 收到的 JSON 字符串,以便在我的代码中进一步使用,但我很难在不编写自定义序列化程序的情况下让它工作。

更喜欢作为编写自定义序列化程序的解决方案,但如果这是唯一可能的方法,我会编写一个。

此外,我认为我收到的数据是一个奇怪的 JSON,因为我请求的列表不是使用 [] 作为列表发送的,而是作为使用 {} 的对象发送的

我收到以下列表/对象(缩写):

{
"results": {
"ALL": {
"currencyName": "Albanian Lek",
"currencySymbol": "Lek",
"id": "ALL"
},
"XCD": {
"currencyName": "East Caribbean Dollar",
"currencySymbol": "$",
"id": "XCD"
},
"EUR": {
"currencyName": "Euro",
"currencySymbol": "â?¬",
"id": "EUR"
},
"BBD": {
"currencyName": "Barbadian Dollar",
"currencySymbol": "$",
"id": "BBD"
},
"BTN": {
"currencyName": "Bhutanese Ngultrum",
"id": "BTN"
},
"BND": {
"currencyName": "Brunei Dollar",
"currencySymbol": "$",
"id": "BND"
}
}
}

我像这样为内部对象创建了我的第一个 POJO:

public class CurrencyDTO implements Serializable {

private String currencyName;
private String currencySymbol;
private String currencyId;


@JsonCreator
public CurrencyDTO( @JsonProperty( "currencyName" ) String currencyName, @JsonProperty( "currencySymbol" ) String currencySymbol,
@JsonProperty( "id" ) String currencyId )
{
this.currencyId = currencyId;
this.currencyName = currencyName;
this.currencySymbol = currencySymbol;
}
}

这本身就很好。现在我写了另一个 POJO 作为数据的包装器,上面一层看起来像这样:

public class CurrencyListDTO implements Serializable {

private List<Map<String, CurrencyDTO>> results;

public CurrencyListDTO()
{
}

}

添加注释 @JsonAnySetter 或使用 @JsonCreator 都没有帮助,所以我再次删除了它们,现在我想知道哪个小技巧可以启用 json 的正确序列化。

我的异常(exception)情况如下:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
at [Source: (String)"{"results":{"ALL":{"currencyName":"Albanian Lek","currencySymbol":"Lek","id":"ALL"},"XCD":{"currencyName":"East Caribbean Dollar","currencySymbol":"$","id":"XCD"},"EUR":{"currencyName":"Euro","currencySymbol":"â?¬","id":"EUR"},"BBD":{"currencyName":"Barbadian Dollar","currencySymbol":"$","id":"BBD"},"BTN":{"currencyName":"Bhutanese Ngultrum","id":"BTN"},"BND":{"currencyName":"Brunei Dollar","currencySymbol":"$","id":"BND"},"XAF":{"currencyName":"Central African CFA Franc","id":"XAF"},"CUP":{"cur"[truncated 10515 chars]; line: 1, column: 12] (through reference chain: com.nico.Banking.api.data.dto.CurrencyListDTO["results"])

最佳答案

您应该将 CurrencyListDTO 更改为:

public class CurrencyListDTO {
private Map<String, CurrencyDTO> results;
// getters and setters
}

因为响应对象中的results字段是另一个以currencyId为键的对象,没有数组。

然后您可以像这样创建您的货币列表:

ObjectMapper mapper = new ObjectMapper();
CurrencyListDTO result = mapper.readValue(json, CurrencyListDTO.class);
List<CurrencyDTO> currencies = new ArrayList<>(result.getResults().values());

关于java - 如果没有自定义序列化程序,是否可以对这个字符串进行 Jackson 序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119251/

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