前面一篇《fastjson json字符串和JavaBean、List、Map及复杂集合类型的相互转换》我们讨论了json和javabean之间的转换,在实际应用中发现,我们举得例子还不够复杂。
如果说javabean中嵌套了其他javabean,并且嵌套了复杂List、Map等的情况时,fastjson是否还能很好的支持这个转换呢?答案是肯定的,fastjson完全支持。
A.java
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Map;
public class A {
String name;
String gender;
List<String> hobby;
List<Map<String, String>> xxx;
B b;
Map<C, List<Map<Integer, C>>> bListMap;
public A() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
public List<Map<String, String>> getXxx() {
return xxx;
}
public void setXxx(List<Map<String, String>> xxx) {
this.xxx = xxx;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
public Map<C, List<Map<Integer, C>>> getbListMap() {
return bListMap;
}
public void setbListMap(Map<C, List<Map<Integer, C>>> bListMap) {
this.bListMap = bListMap;
}
}
B.java
import java.util.List;
import java.util.Map;
public class B {
String sa;
int sb;
List integerList;
Map> stringListMap;
public B() {
}
public String getSa() {
return sa;
}
public void setSa(String sa) {
this.sa = sa;
}
public int getSb() {
return sb;
}
public void setSb(int sb) {
this.sb = sb;
}
public List getIntegerList() {
return integerList;
}
public void setIntegerList(List integerList) {
this.integerList = integerList;
}
public Map> getStringListMap() {
return stringListMap;
}
public void setStringListMap(Map> stringListMap) {
this.stringListMap = stringListMap;
}
}
C.java
public class C {
String aaa;
int bbb;
Float ccc;
public C() {
}
public C(String aaa, int bbb, float ccc) {
this.aaa = aaa;
this.bbb = bbb;
this.ccc = ccc;
}
public String getAaa() {
return aaa;
}
public void setAaa(String aaa) {
this.aaa = aaa;
}
public int getBbb() {
return bbb;
}
public void setBbb(int bbb) {
this.bbb = bbb;
}
public float getCcc() {
return ccc;
}
public void setCcc(float ccc) {
this.ccc = ccc;
}
}
Test.java
class Test {
public static void main(String[] args) {
A oa = new A();
oa.setName("wei.hu");
oa.setGender("man");
List hobbys = Lists.newArrayList("basketball", "pingpang", "footbool");
oa.setHobby(hobbys);
Map map1 = Maps.newHashMap();
map1.put("key1", "value1");
map1.put("key2", "value2");
map1.put("key3", "value3");
Map map2 = Maps.newHashMap();
map2.put("key1", "value1");
map2.put("key2", "value2");
map2.put("key3", "value3");
List
是的,你没有看错,通过JSON.parseObject(String, Class)我们就可以将一个json字符串转换成一个足够复杂的javabean。