gpt4 book ai didi

java - 如何用 Jackson 反序列化将每个映射条目的键注入(inject)到相应的值对象中?

转载 作者:行者123 更新时间:2023-12-02 04:25:35 27 4
gpt4 key购买 nike

我有以下 json 对象。

{
"items": {
"item-1": {"type":"A", "desc": "blabla"},
"item-2": {"type":"B", "desc": "blabla"},
...
}
}

我想将此 json 对象映射到以下 java 对象。

public class MyObject {
private final Map<String,Item> items;

@JsonCreator
public MyObject(@JsonProperty Map<String,Item> items) { ... }
...
}

class Item {
private final string id; <-- ideally could be initialized by the corresponding key in the map
private final String type;
private final String desc;

public Item(@JsonProperty String id, @JsonProperty String type, @JsonProperty String desc) { ... }
}

仅当我提供以下 json 对象时,反序列化才有效。

{
"items": {
"item-1": {"id":"item-1", "type":"A", "desc": "blabla"},
"item-2": {"id":"item-2", "type":"B", "desc": "blabla"},
...
}
}

这并不理想(即:冗余 -> 容易出错)。

是否有 jackson 注释来解决这个常见模式,或者其他方式?我找不到类似 @JsonProperty(useKeyMap=true) 的内容。

更新:我对构造函数的 id 参数初始化为 null 的解决方案不感兴趣。

最佳答案

I have tried your example you need to put @Json creator annotation on your Items class constructor as well.

Below is the modified code.

class Item {

private final String id;

private final String type;

private final String desc;

@JsonCreator
public Item( @JsonProperty("id")String id, @JsonProperty("type")String type, @JsonProperty("desc")String desc) {
this.id = id;
this.type = type;
this.desc = desc;
}
}

class MyObject {
private final Map<String,Item> items;

@JsonCreator
public MyObject(@JsonProperty("items") Map<String, Item> items) {
this.items = items;
}

它反序列化 json,如果您不提供 id 的值,则默认值为 null。

关于java - 如何用 Jackson 反序列化将每个映射条目的键注入(inject)到相应的值对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35371460/

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