一·安卓原生解析
1.使用JSONObject
string json="************************";//json数据
JSONObject jsonObject=new JSONObject(json);//得到jsonobject对象
string id=jsonObject.optxxx("id");//optxxx在不存在值得情况下会抛异常,也可使用getxxx方法,但此方法不会抛异常操作。
string name=jsonObject.optxxx("name");
studenBean student =new studentBean(id,name);//在将得到的数据进行封装,假设已写好studentBean。
若json数据比较复杂,就需要解析一层封装一层。
若是比较特殊,就需要手动了,嘿嘿嘿!
到此json数据转换为Java对象的过程就结束了。
二·强大的Gson框架
首先添加gson依赖
implementation group: 'com.google.code.gson', name: 'gson', version: '2.8.5'
1.json数据转化为Java对象或集合
String json="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";//准备好json数据
Gson gson=new Gson();//创建Gson对象
XXX xxx=gson.fromJson(json,类名.class);//得到单个对象
XXX xxx=gson.fromJson(json,new TypeToken<XXX>(){});//得到集合
2.java对象或集合转化为json数据
Gson gson=new Gson();//创建Gson对象
String json=gson.toJson(Object object);//添加对象,即可得到json数据。
Gson让json解析更简单!
三·极致的fastjson框架
1.json数据转化为Java对象或集合
String json="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";//准备好json数据
XXX xxx=JSON.parseObject(json,类名.class);//得到单个对象
XXX xxx=JSON.parseArray(json,XXX.class);//得到集合
2.java对象或集合转化为json数据
String json=JSON.toJSONString(Object object);//添加对象,即可得到json数据。
fastjson性能极致!