gpt4 book ai didi

java - 使用 Jackson 将 JSON 反序列化为包含集合的 Java 对象

转载 作者:行者123 更新时间:2023-12-01 18:48:43 24 4
gpt4 key购买 nike

我正在与 Jackson 进行一个非常简单的测试。我有一个类,并使用它的对象作为 Jersey 方法的参数和返回值。类(class)是:

import java.util.List;

public class TestJsonArray {

private List<String> testString;

public List<String> getTestString() {
return testString;
}

public void setTestString(List<String> testString) {
this.testString = testString;
}
}

我有一个 Jersey 方法,尝试将一个字符串添加到列表测试字符串

@Path("/arrayObj")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Object createObjectArray(@QueryParam("param") String object) throws JsonGenerationException, JsonMappingException, IOException {
ObjectMapper objectMapper = new ObjectMapper();
TestJsonArray convertValue = objectMapper.convertValue(object, TestJsonArray.class);
convertValue.getTestString().add("hello");
return objectMapper.writeValueAsString(convertValue);
}

当我使用参数调用此方法时

{"testString":["Hi"]}

我遇到异常:

java.lang.IllegalArgumentException: Can not construct instance of test.rest.TestJsonArray, problem: no suitable creator method found to deserialize from JSON String
at [Source: N/A; line: -1, column: -1]

反序列化过程中抛出异常:

TestJsonArray convertValue = objectMapper.convertValue(object, TestJsonArray.class);

我想知道为什么会抛出这个异常。我做错了什么?

最佳答案

尝试使用ObjectMapperreadValue方法而不是convertValue

objectMapper.readValue(json, TestJsonArray.class);

这应该有效。

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

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