gpt4 book ai didi

java - 无法以 POJO 类作为值反序列化 Map

转载 作者:行者123 更新时间:2023-11-29 08:51:59 25 4
gpt4 key购买 nike

我正在尝试将以下 JSON 结构解析为自定义 Java 对象模型,如下所示。

当我运行测试时出现错误:

org.codehaus.jackson.map.JsonMappingException: Unrecognized field "arbitraryKey1" (Class DemoClass), not marked as ignorable

如何在 MiddleClass 中注释“叶子”Map

{
"fieldA": {
"arbitraryKey1" : {
"innerFieldA": "foo",
"innerFieldB": "bar"
},
"arbitraryKey2" : {
"innerFieldA": "testing",
"innerFieldB": "123"
}
},
"fieldB": {
"arbitraryKeyX" : {
"innerFieldA": "more",
"innerFieldB": "testing"
}
}
}

这是我的 java 类:

public class DemoClass {
@JsonProperty
public MiddleClass fieldA;

@JsonProperty
public MiddleClass fieldB;
}

public class MiddleClass {
public Map<String, LeafClass> leaves;

public LeafClass getLeaf( String name ) { return leaves.get(name); }
}

public class LeafClass {
public String innerFieldA;
public String innerFieldB;
}

public class DemoTest {
@Test
public void testReadValue() {
DemoClass demo = ObjectMapper().readValue( json, DemoClass.class );
assertEquals( demo.fieldA.leaves.get("arbitraryKey1").innerFieldA, "foo" );
assertEquals( demo.fieldB.getLeaf("arbitraryKeyX").innerFieldB, "testing" );
}
}

最佳答案

您的 MiddelClass 应如下所示:

class MiddleClass {

public Map<String, LeafClass> leaves = new HashMap<String, LeafClass>();

@JsonAnyGetter
public LeafClass getLeaf(String name) {
return leaves.get(name);
}

@JsonAnySetter
public void addLeaf(String key, LeafClass value) {
leaves.put(key, value);
}

@Override
public String toString() {
return leaves.toString();
}
}

@JsonAnySetter 注释可以解决问题。

关于java - 无法以 POJO 类作为值反序列化 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22367206/

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