使用杰克逊

时间:2020-06-12 22:11:26

标签: 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只需要最后一个“朋友”,但我需要两个。 我知道JSONObject使用Map进行转换,所以这就是为什么要使用最后一个。

结果: 联系人(id = 5ee2e2f780bc8e7511a65de9,朋友= [{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,但没有成功。 我对此卡住了。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

还要创建“朋友”的POJO类,然后像

一样编辑“联系人”类
public class Contacts {
   String id;
   List<Friend> friends;
}

然后您应该获得Friend项目列表

相关问题