Jackson:Json具有Json数组,java类具有另一个java类的列表
我正在使用jackson 2.6.x 我无法将json转换为java类Jackson:Json具有Json数组,java类具有另一个java类的列表,java,json,jackson,Java,Json,Jackson,我正在使用jackson 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; } @JsonPrope
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;
}}
我的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在System.out.print(pt.toString)上不打印任何内容 正如javadocs中所述,
@JsonRootName
不能单独工作。
您应该将其与序列化功能#WRAP_ROOT_VALUE
和/或反序列化功能#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
,您是否尝试使用@JSonCreator命令为ParentTest类指定构造函数?您的测试用例失败,因为Test
类的构造函数不合适。
public class TestWrapper {
@JsonProperty("Test")
private Test test;
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
}
public class TestWrapper {
@JsonProperty("Test")
private Test test;
public Test getTest() {
return test;
}
public void setTest(Test test) {
this.test = test;
}
}