我正在使用杰克逊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;
}}
我的杰森是
{"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);上不打印任何内容;
@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;
}
}
并使用它,而不是Test
在ParentTest
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句