gpt4 book ai didi

java - 使用 Jackson 将字符串转换为对象

转载 作者:行者123 更新时间:2023-12-01 11:32:58 26 4
gpt4 key购买 nike

我将获得以下格式的 JSON

"address":
{
"type": "Temporary"
}

以下是 Address 类。

class Address
{
AddressType type;
public Address(AddressType type)
{
this.type = type;
}
}

class AddressType
{
private String type;
public AddressType(String type)
{
this.type = type;
}
}

如果 Address.java 的类型为 String,则从 JSON 转换为 Address 对象会更容易。但我不确定如何将 JSON 转换为 Address 对象,其中“type”将转换为 AddressType 对象。我将使用 jackson 库。请帮助我。

最佳答案

对于 AddressType 本身,它应该按原样工作,因为 Jackson 会将字符串转换为对象,其中该对象具有采用单个字符串的公共(public)构造函数。

对于序列化,您可能需要使用@JsonValue注释类型字段或getType方法来执行反向转换。

要使用给定类型调用 Address 构造函数,您需要在构造函数上使用 @JsonCreator 注释,并在其参数上使用 @JsonProperty 注释:

@JsonCreator
public Address(@JsonProperty("type") AddressType type) { ... }

关于java - 使用 Jackson 将字符串转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30272094/

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