我一直在寻找这个问题的解决方案,但找不到所以问这个问题。
我有一些看起来像这样的数据
{
"data": [
{
"id": "5ab892c71810e201e81b9d39",
"isSignedUpUsingFb": false,
"personalInformation": {
"firstName": "jio",
"lastName": "g",
"mobileNumber": "1234567890",
},
"accountBalance": 0,
}
]
},
我想写一段java代码把数据结构改成这样
{
"data": [
{
"id": "5ab892c71810e201e81b9d39",
"isSignedUpUsingFb": false,
"personalInformation_firstName":"jio",
"personalInformation_lastNAme":"g",
"personalInformation_mobileNumber":"1234567890",
"accountBalance": 0,
}
]
},
我正在从数据库中获取数据:
@Override
public List<User> getAllUsers() {
logger.debug("entering all users method");
List<User> allUsers=mongoOperations.findAll(User.class);
for (User user : allUsers) {
PersonalInformation info=user.getPersonalInformation());
//manipulation code here
user.setPersonalInformation(info);
}
return allUsers;
}
所以我想编写一个逻辑,以便我可以将数据转换为所需的格式并向其发送返回类型。我知道如何使用 J 查询做同样的事情,但我想在后端做,所以上面的任何代码或任何链接都会有所帮助。
最佳答案
我喜欢一个非常简单的解决方案。所以,基本上,当我们为嵌套数据创建对象时,我们在 JAVA 中像这样创建它。
public MyClass{
public String name;
public String contact;
public PersonalInformation personalinformation;
//setters and getter here
}
这会给我数据
"MyClass":{
"name": "abc",
"contact": "12345",
"personalInformation":{
"address": "asdasdasdad",
"city":"asdadad",
"pin": "asdfg",
}
}
因此,要删除此嵌套数据,我们需要使用 @JsonUnwrapped
来删除所有嵌套对象并将其添加到我们的主对象中。
public MyClass{
public String name;
public String contact;
@JsonUnwrapped
public PersonalInformation personalinformation;
//setters and getter here
}
这会将数据结构更改为:
"MyClass":{
"name": "abc",
"contact": "12345",
"address": "asdasdasdad",
"city":"asdadad",
"pin": "asdfg",
}
有关更多引用,您可以查看此链接 http://fasterxml.github.io/jackson-annotations/javadoc/2.0.0/com/fasterxml/jackson/annotation/JsonUnwrapped.html
希望这会有所帮助。
关于java - 如何在java中操作嵌套的Json数据去嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49492361/