繁体   English   中英

使用Jackson将JSON反序列化为Java Object containsg集合

[英]Deserialize JSON to Java Object containg Collection using Jackson

我正在对杰克逊做一个非常简单的测试。 我有一个类,并将其对象用作Jersey方法的参数和返回值。 该类是:

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”:[ “您好”]}

我有一个例外:

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

我想知道为什么抛出此异常。 我究竟做错了什么?

尝试使用ObjectMapper readValue方法而不是convertValue

objectMapper.readValue(json, TestJsonArray.class);

这应该工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM