【问题标题】:Jackson: Json having json array to java class having list of another Java class杰克逊:Json 具有 json 数组到具有另一个 Java 类列表的 Java 类
【发布时间】:2015-10-09 14:14:41
【问题描述】:

我正在使用杰克逊 2.6.x 我无法将 json 转换为 java 类

public class ParentTest {
@JsonProperty("ParentTest")
public List<Test> getTestList() {
    return testList;
}

public void setTestList(List<Test> testList) {
    this.testList = testList;
}

@JsonProperty("ParentTest")
List<Test> testList;

public ParentTest(List<Test> testList)
{   
    this.testList = testList;
}

public ParentTest()
{
    super();
    testList = new ArrayList<Test>();
}

public String toString()
{
    String r = "";
    if(testList!=null)
    for(Test t : testList)
    {
        r += "Test:"+t.field1+t.field2; 
    }
    else
        r = "null";
    return r;
}}

而用于列表的类是

@JsonRootName("Test")public class Test {
@JsonProperty("field1")
String field1;
@JsonProperty("field2")
String field2;
public Test(String field1,String field2)
{

    this.field1 = field1;

    this.field2 = field2;
}
public String getField1() {
    return field1;
}
public void setField1(String field1) {
    this.field1 = field1;
}
public String getField2() {
    return field2;
}
public void setField2(String field2) {
    this.field2 = field2;
}}

我的 Json 是

{"ParentTest":   [{
"Test":{
        "field1":"t1",
        "field2":"t2"
         }
},
{
"Test":{
        "field1":"t3",
        "field2":"t4"
         }
}]}

为了阅读它,我已经使用了

public final class HandlerJacksonUtils {
private static ObjectMapper m = new ObjectMapper();
private static JsonFactory jf = new JsonFactory();

    public static <T> Object fromJson(String jsonAsString, Class<T> pojoClass) throws IOException {
        m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return m.readValue(jsonAsString, pojoClass);
    }}

然后

ParentTest pt = (ParentTest) HandlerJacksonUtils.fromJson(json, ParentTest.class);

ParentTest 对象 pt 在 System.out.print(pt.toString) 上不打印任何内容;

【问题讨论】:

  • 你试过用@JSonCreator注解为你的ParentTest类指定一个构造函数吗?
  • 你的测试用例对我来说失败了,因为 Test 类的构造函数不合适。

标签: java json jackson


【解决方案1】:

@JsonRootName 不能单独工作,如 javadocs 中所述。 您应该将它与SerializationFeature#WRAP_ROOT_VALUE 和/或DeserializationFeature#UNWRAP_ROOT_VALUE 结合使用。 但它仅适用于您想要序列化/反序列化的根对象。因此,它不适用于您的情况。 相反,您可以为 Test 创建一个包装类

public class TestWrapper {

    @JsonProperty("Test")
    private Test test;

    public Test getTest() {
        return test;
    }

    public void setTest(Test test) {
        this.test = test;
    }
}

并在ParentTest 中使用它代替Test

【讨论】:

    猜你喜欢
    • 2014-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    • 1970-01-01
    • 2015-02-23
    • 2013-09-12
    • 2016-12-31
    相关资源
    最近更新 更多