gpt4 book ai didi

java - 将带有 String 成员变量的对象转换为 json 序列化中的单个字符串的简单方法 (Jackson)

转载 作者:行者123 更新时间:2023-11-30 01:56:43 25 4
gpt4 key购买 nike

有没有一种简单/开箱即用的方法在序列化时将具有单个字符串作为成员变量的对象转换为单个字符串JacksonJSON 格式?

例如,假设我有以下对象

public class ContextAttributeIdentity implements Serializable {

private String attributeName;
//getters setters constructor ommitted
}

当对象被序列化时,它给出以下json

    "contextAttributeIdentity": {
"attributeName": "age"
}

我想在序列化时将其转换为单个 String 对象,如下所示:

"attributeName": "age"

我的案例场景:

public class Context {
int id;
List<ContextAttribute> contextattributes
}

public class ContextAttribute{
ContextAttributeIdentity contextAttributeIdentity;
}

public class ContextAttributeIdentity {
String attributeName;
}

当我序列化 Context 对象时,它会变成这样的 json 格式

{ 
"id": "1",
"contextAttributes": [
{
"contextAttributeIdentity": {
"attributeName": "name"
}
},
{
"contextAttributeIdentity": {
"attributeName": "age"
}
}
]
}

我希望这样显示

 { 
"id": "1",
"contextAttributes": [
{
"attributeName": "name"
},
{
"attributeName": "age"
}
]
}

最佳答案

如果ContextAttributeIdentity是其他对象的成员,您可以使用@JsonUnwrapped对其进行注释,如下所示:

public class SomeClass {
@JsonUnwrapped
private ContextAttributeIdentity contextAttributeIdentity;
}

关于java - 将带有 String 成员变量的对象转换为 json 序列化中的单个字符串的简单方法 (Jackson),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54204038/

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