Gson是一个超好用的json-对象相互转换的工具。如果您还没有,可以到这里去下载gson2.2.2.jar
首先准备两个类,如下:
public class One { int integer = 10; String a = null; Two comTwo = new Two(); @Override public String toString() { return "integer: " + integer + " ; a: " + a +" ; "+comTwo.toString() ; } } public static class Two { int twoINt; String twoStr; @Override public String toString() { // TODO Auto-generated method stub return "twoInt: " + twoINt + " ; twoStr: " + twoStr; } }
new 一个One对象,将其转换为json:
<span style="color:#006600;">Gson gson = new Gson(); One one = new One(); String oneJstr = gson.toJson(one); System.out.println(oneJstr);</span>
结果为:
<span style="color:#006600;">{"integer":10,"comTwo":{"twoINt":0}}</span>
Gson gson = new Gson(); One one = new One(); one.a = " zhang ting"; String oneJstr = gson.toJson(one); System.out.println(oneJstr);
<span style="color:#990000;">{"integer":10,"a":" zhang ting","comTwo":{"twoINt":0}}</span>
String js = "{\"integer\":10,\"comTwo\":{\"twoInt\":20}}"; One oneObj = gson.fromJson(js, One.class); System.out.println(oneObj);结果为:
<span style="color:#006600;">integer: 10 ; a: null ; twoInt: 0 ; twoStr: null</span>
public static class OneChild extends One{ String three = "i'm three "; List<String> list; List<CompObj> obList; public OneChild(){ list = new ArrayList<String>(); list.add("XXX"); list.add("ting"); obList = new ArrayList<CompObj>(); CompObj d1 = new CompObj(); d1.data="good"; CompObj d2 = new CompObj(); d2.data = "zhang"; obList.add(d1); obList.add(d2); } }
public static class CompObj{ String data = " comp obj"; }
OneChild child = new OneChild(); String thJstr = gson.toJson(child); System.out.println(thJstr);
<span style="color:#006600;">{"three":"i\u0027m three ","list":["XXX","ting"],"obList":[{"data":"good"},{"data":"zhang"}],"integer":10,"comTwo":{"twoINt":0}}</span>
Type listType = new TypeToken<List<String>>() {}.getType(); List<String> target = new LinkedList<String>(); target.add("blah"); target.add("gao"); target.add("zhang ting"); // Gson gson = new Gson(); String json = gson.toJson(target, listType); System.out.println(json);
<span style="color:#990000;">["blah","gao","zhang ting"]</span>
1、json数据中的key要和java对象中的变量名一致(区分大小写)
2、只有java对象有值(默认值都可以)才会转化到json数据中。
3、java对象中的变量不必和json数据中的key一一对应。
4、子类中找不到的变量会自动到父类中寻找。
原文地址:http://blog.csdn.net/sun_star1chen/article/details/44086149