试验一下
类图
po类
1. C3public class C3 { private C1 c1; private C2 c2; public C1 getC1() { return c1; } public void setC1(C1 c1) { this.c1 = c1; } public C2 getC2() { return c2; } public void setC2(C2 c2) { this.c2 = c2; } @Override public String toString() { return "C3{" + "c1=" + c1 + ",c2=" + c2 + '}'; } }
2. C1
public class C1 { private String a1; private List<C4> c4 = new ArrayList<>(); public List<C4> getC4() { return c4; } public void setC4(List<C4> c4) { this.c4 = c4; } public String getA1() { return a1; } public void setA1(String a1) { this.a1 = a1; } @Override public String toString() { return "C1{" + "a1='" + a1 + '\'' + ",c4=" + c4 + '}'; } }
3. C2
public class C2 { private String a2; public String getA2() { return a2; } public void setA2(String a2) { this.a2 = a2; } @Override public String toString() { return "C2{" + "a2='" + a2 + '\'' + '}'; } }
4. C4
public class C4 { private String a4; public String getA4() { return a4; } public void setA4(String a4) { this.a4 = a4; } @Override public String toString() { return "C4{" + "a4='" + a4 + '\'' + '}'; } }
测试类
@Test public void testFastJson(){ String s = "{\"c1\":{\"a1\":\"1\",\"c4\":[{\"a4\":\"4\"},{\"a4\":\"5\"}]},\"c2\":{\"a2\":\"3\"}}".trim(); C3 c3 = JSON.parSEObject(s,C3.class); System.out.println(c3); }
可以解析
注意两点:
1. 类的成员的命名要与json中对应的“对象/数组”名称一致
2. 嵌套成内部类也是可以解析的,参考:fastjson可以解析嵌套的内部类吗?
可以说fastjson还是很强大的