参考地址:
http://www.stormzhang.com/android/2014/05/22/android-gson/
我的示例代码:
public void doGsonTest(View view) { //参考文档 http://www.stormzhang.com/android/2014/05/22/android-gson/ Log.d("lsl","doGsonTest"); String JSON_DATA = "{"id": 101,"body": "It is my post","number": 0.13,"created_at": "2014-05-22 19:12:38"}"; Foo foo = new Gson().fromJson(JSON_DATA, Foo.class); LogUtil.d("lsl","id="+foo.id+"body="+foo.body+"number="+foo.number+"created_at="+foo.created_at); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd"); Gson gson = gsonBuilder.create(); foo = gson.fromJson(JSON_DATA, Foo.class); LogUtil.d("lsl","id="+foo.id+"body="+foo.body+"number="+foo.number+"created_at="+foo.created_at); JSON_DATA = "[{"id": 102,"body": "It is my post","number": 0.13,"created_at": "2014-05-22 19:12:38"},{"id": 103,"body": "It is my post","number": 0.13,"created_at": "2014-05-22 19:12:38"}]"; Foo[] foos = new Gson().fromJson(JSON_DATA, Foo[].class); List<Foo> foosList = Arrays.asList(foos); for(Foo vo : foosList){ LogUtil.d("lsl","id="+vo.id+"body="+vo.body+"number="+vo.number+"created_at="+vo.created_at); } LogUtil.d("lsl","============merchandiose============="); JSON_DATA = "{"op_type": 10002,"code": "0","msg": "success","data":[{"id": 104,"name": "apple","kind_name": "food","price": 0.13,"created_at": "2014-05-22 19:12:38"},{"id": 105,"name": "orange","kind_name": "food","price": 0.13,"created_at": "2014-05-22 19:12:38"}]}"; MechandiseListModel mObj = new Gson().fromJson(JSON_DATA, MechandiseListModel.class); LogUtil.d("lsl","op_type="+mObj.op_type +"code="+mObj.code +"msg="+mObj.msg ); List<Mechandise> mList = mObj.data; for(Mechandise m : mList){ LogUtil.d("lsl","" + "id="+m.id+"name="+m.name+"kind_name="+m.kind_name+ "price="+m.price+"created_at="+m.created_at ); } } public class MechandiseListModel { public int op_type; public int code; public String msg; List<Mechandise> data; } public class Mechandise { public int id; public String name; public String kind_name; public float price; public String created_at; } public class Foo { public int id; public String body; public float number; public String created_at; }