问题描述
我正在将json转换为java对象,但是我没有得到想要的东西.我在json中复制了键"friend".
Im converting a json to a java object but I'm not getting what I want.I have duplicated keys "friend" in my json.
我的json:
{
"id" : "5ee2e2f780bc8e7511a65de9",
"friends": [{
"friend": {
"id": 1,
"name": "Priscilla Lynch"
},
"friend": {
"id": 2,
"name": "William Lawrence"
}
}]
}
使用ObjectMapper中的readValue只需要最后一个朋友",但我需要两个.我知道JSONObject使用Map进行转换,所以这就是为什么要使用最后一个.
Using readValue from ObjectMapper only takes the last one "friend" but I need both.I know JSONObject use Map to convert so that's why it is taking the last one.
结果:联系人(id = 5ee2e2f780bc8e7511a65de9,朋友= [{friend = {id = 2,name = William Lawrence}}])
Result:Contacts(id=5ee2e2f780bc8e7511a65de9, friends=[{friend={id=2, name=William Lawrence}}])
ObjectMapper mapper = new ObjectMapper();
Contacts contacts = mapper.readValue(json, Contacts.class);
联系Pojo:
@Getter
@Setter
@ToString
public class Contacts {
String id;
List<Object> friends;
}
我想要所有朋友的名单.由于提供json的服务不在我手中,因此我需要找到一种解决方法.我尝试从apache.commons使用MultiMap,但没有成功.我对此卡住了.
I want a list of all friends. As the service whose provide the json is not in my hand I need to find a way to solve it.I tried use MultiMap from apache.commons but no success.Im stuck on this.
推荐答案
当您的JSON Object
具有重复的字段时,可以使用com.fasterxml.jackson.annotation.JsonAnySetter
批注.结果将为List<List<X>>
,因此,您可以使用flatMap
方法创建List<X>
.参见以下示例:
When you have a JSON Object
with duplicated fields you can use com.fasterxml.jackson.annotation.JsonAnySetter
annotation. Result will be a List<List<X>>
so, you can use flatMap
method to create List<X>
. See below example:
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DuplicatedFieldsInJsonObjectApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
ObjectMapper mapper = JsonMapper.builder().build();
Contacts contacts = mapper.readValue(jsonFile, Contacts.class);
System.out.println(contacts.getUnwrappedFriends());
}
}
@Getter
@Setter
@ToString
class Contacts {
String id;
List<Friends> friends;
public List<Friend> getUnwrappedFriends() {
return friends.stream().flatMap(f -> f.getFriends().stream()).collect(Collectors.toList());
}
}
class Friends {
private List<Friend> friends = new ArrayList<>();
@JsonAnySetter
public void setAny(String property, Friend friend) {
friends.add(friend);
}
public List<Friend> getFriends() {
return friends;
}
}
@Getter
@Setter
@ToString
class Friend {
int id;
String name;
}
上面的代码显示:
[Friend(id=1, name=Priscilla Lynch), Friend(id=2, name=William Lawrence)]
这篇关于用杰克逊用重复的键转换JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!