java - 使用 jackson 转换带有重复键的 JSON

标签 java json jackson jackson-databind

我正在将 json 转换为 java 对象,但没有得到我想要的。 我的 json 中有重复的键“ friend ”。

我的JSON:

{
    "id" : "5ee2e2f780bc8e7511a65de9",
    "friends": [{
        "friend": {
            "id": 1,
            "name": "Priscilla Lynch"
        },
        "friend": {
            "id": 2,
            "name": "William Lawrence"
        }
    }]
}

使用 ObjectMapper 的 readValue 只需要最后一个“ friend ”,但我需要两者。 我知道 JSONObject 使用 Map 进行转换,所以这就是它采用最后一个的原因。

结果: 联系人(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;
}

我想要一个所有 friend 的列表。由于提供json的服务不在我手上,我需要找到一种方法来解决它。 我尝试使用 apache.commons 中的 MultiMap 但没有成功。 我坚持这一点。

最佳答案

当你有一个 JSON Object对于重复的字段,您可以使用 com.fasterxml.jackson.annotation.JsonAnySetter注解。结果将是 List<List<X>>所以,你可以使用 flatMap创建方法 List<X> .请参见以下示例:

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)]

关于java - 使用 jackson 转换带有重复键的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62353185/

相关文章:

Kotlin 数据类和 LocalDateTime

java - 如何将遗留 Java/J2EE 网站移植到现代脚本语言(PHP、Python/Django 等)?

java - "Unrecognized token ' com ': was expecting (' 真 ', ' 假 ' or ' 空 ')"

java - 如何在调用另一个构造函数之前拆分字符串

java - Android与json解析

java - Jackson-jr 读取多态ArrayList

java - Java InitialDirContext() 的用途/好处是什么?

python - 如何将此系列转换为嵌套 json 字符串?

java - 无法将文本文件转换为 json

java - 如何使用java将csv转换为json,数值不带引号