gpt4 book ai didi

java - 使用 Jackson 2 将 JSON 反序列化为 Java

转载 作者:行者123 更新时间:2023-11-30 04:30:37 24 4
gpt4 key购买 nike

我有一个 JSON:

{"evaluationPart": {
"generatedId": "48D5181DB8704F8AB5FC998964AD9075",
"evaluationQuestionPartOption": {
"generatedId": "48D5181DB8704F8AB5FC998964AD9075"
}
}}

我已经为它创建了 java 类来表示它:

根类:

@JsonIgnoreProperties(value = {"evaluationPart"})
public class JsonEvaluationPart {

@JsonProperty("generatedId")
private String generatedId;

@JsonProperty("evaluationQuestionPartOption")
private JsonQuestionOption questionOption;

public String getGeneratedId() {
return generatedId;
}

public void setGeneratedId(String generatedId) {
this.generatedId = generatedId;
}

public JsonQuestionOption getQuestionOption() {
return questionOption;
}

public void setQuestionOption(JsonQuestionOption questionOption) {
this.questionOption = questionOption;
}
}

以及 JsonQuestionOption 类:

public class JsonQuestionOption {

@JsonProperty("generatedId")
private String generatedId;

public String getGeneratedId() {
return generatedId;
}

public void setGeneratedId(String generatedId) {
this.generatedId = generatedId;
}
}

我编写了一个小型 JUnit 测试来检查它的运行情况:

public class JsonReaderTest {

/**
* Logger for this class.
*/
private static final Logger LOGGER = LoggerFactory.getLogger(JsonReaderTest.class);

private ObjectMapper objectMapper;

private static final String JSON = "{\"evaluationPart\": {\n" +
" \"generatedId\": \"48D5181DB8704F8AB5FC998964AD9075\",\n" +
" \"evaluationQuestionPartOption\": {\n" +
" \"generatedId\": \"48D5181DB8704F8AB5FC998964AD9075\"\n" +
" }\n" +
"}}";

@Before
public void setUp()
throws Exception {
LOGGER.debug("Creating the object mapper.");
objectMapper = new ObjectMapper();
LOGGER.debug("Object mapper successfully created. {}", objectMapper);
}

@Test
public void testJsonReader()
throws Exception {

JsonEvaluationPart partType = objectMapper.readValue(JSON, JsonEvaluationPart.class);
assertNotNull(partType);

LOGGER.debug("Part: {}.", partType);

assertEquals(partType.getGeneratedId(), "48D5181DB8704F8AB5FC998964AD9075");
assertEquals(partType.getQuestionOption().getGeneratedId(), "48D5181DB8704F8AB5FC998964AD9075");
}

}

问题是当我像这样读取 JSON 时:

JsonEvaluationPart partType = objectMapper.readValue(JSON, JsonEvaluationPart.class);

partType 中的所有属性均为 null。我在这里做错了什么以及如何解决这个问题?

最佳答案

根据文档JsonIgnoreProperties意思是:

Annotation that can be used to either suppress serialization of properties 
(during serialization), or ignore processing of JSON properties read (during
deserialization).

尝试替换:

@JsonIgnoreProperties(value = {"evaluationPart"}) 

与:

@JsonTypeName("evaluationPart") 

关于java - 使用 Jackson 2 将 JSON 反序列化为 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14748992/

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