JSON封装和解析(通过GSON)
在app的build.gradle中
加入
// 添加GSON依赖
compile 'com.google.code.gson:gson:2.8.2'
版本可以在maven库
http://mvnrepository.com/artifact/com.squareup.retrofit2/retrofit
输入gson查看
JSONObject和JsonObject区别
1 JSONObject是java提供的原生类 JsonObject是google提供的类
import org.json.JSONObject
import com.google.gson.JsonObject
2 JSONObject用HashMap保存键值对,JsonObject用 LInkedTreeMap 保存键值对
3 对空值处理方式不同
JSONObject: 添加 value 为null,这个键值对会被删掉,读取时会获取不到这个键值对
JsonObject: 添加 value 为null, 可以正常添加 读取时会获取到null的数据
4 toString结果不同
因为JSONObject是用HashMap来保存数据的,所以对它toString的时候可能出现顺序和保存顺序不一致的情况
而JsonObject不存在这个问题
JSON封装
不能直接自己封json String串 因为对于 那种有\r\n的 是不会识别的
而是使用 toJson(Object)的方式去封装Json
这个Object可以是JsonObject或者自己的bean类(但是通过创建bean类的方式会加上了 \ 而有的工具好像是解析不了)
JsonObject jo = new JsonObject();
jo.addProperty("key", value);
mGson = new Gson();
mGson.toJson(jo)
// 要记得加try catch
JSONObject json = new JSONObject();
try {
json.put("widgetName", eventRecord.getEntryName());
} catch (Exception ignored) { }
JSON解析
1 创建一个 JavaBean类
在Bean类中,alt+s打开GSONFormat工具
将JSON数据复制到对话框中
注意:这里创建的getXX,setXX方法的XX是与key键完全一样的
2主类中
主类创建GSON对象
Gson gson = new Gson();
创建
Bean类对象 (如该类名为GetFirstTime)
GetFirstTime getTime = gson.fromJson(str2, GetFirstTime.class);
//获得的json字符串,Bean.class
Bean类调用 getXXX()方法即可获取相应的XXX的键值对的值
str_1 = getTime.getFirstTime();
**可能获取的字符串为空 因为 call线程还未执行完,就执行了后面的 因此 要用异步操作
具体可以参考
http://blog.csdn.net/weixin_37577039/article/details/78556296
用rxjava+retrofit2+okhttp+GSON解析
当然也可以用Handler进行消息异步处理
http://blog.csdn.net/weixin_37577039/article/details/78759727
GSON进行JSON数据的嵌套解析:
如这样的数据
{
"token": "jefawnewfnknafnafnfl1611fawa115g1515165g",
"success": 1,
"userInfo": {
"roleId": 123456,
"saleFlag": 1,
"enterpriseId": 614,
"userId": 704,
"account": "admin366"
},
"msg ": ""
}
创建一个BEAN类,用GSONFormat去自动设置Bean成员和set get方法
在BEAN类的内部,还会有个类
该类声明为public static类型的
并且类中属性与json的数据属性名也一样
具体就不贴出来了 ,直接用GSONFormat对上面的构建就好
重点讲具体怎么解析!
// 外围的,和上面一样 如外围的bean名为Bean0 上面的json string为testJson
Bean0 bean0 = gson.fromJson(testJson, Bean0.class);
String token = bean0 .getToken();
String success= bean0 .getSuccess();
// 内部类解析
Bean0 .UserInfoBean userInfoBean = bean0 .getUserInfo();
roleId = userInfoBean.getRoleId();
GSON解析嵌套数组形式的JSON格式
如下数据:
{
"data": {
"SaleTarget": 0,
"CollectionTotal": 0,
"weekSales": [
{
"weekName": "01-16",
"saleTotal": 0
},
{
"weekName": "01-17",
"saleTotal": 0
},
{
"weekName": "01-18",
"saleTotal": 0
},
{
"weekName": "01-19",
"saleTotal": 0
},
{
"weekName": "前天",
"saleTotal": 0
},
{
"weekName": "昨天",
"saleTotal": 0
},
{
"weekName": "今天",
"saleTotal": 0
}
],
"weekPlans": [
{
"weekName": "前天",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
},
{
"weekName": "昨天",
"weekPlanDetail": [
{
"planSubject": "拜访马化腾",
"planStatus": "待处理"
}
]
},
{
"weekName": "今天",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
},
{
"weekName": "01-23",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
},
{
"weekName": "01-24",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
},
{
"weekName": "01-25",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
},
{
"weekName": "01-26",
"weekPlanDetail": [
{
"planSubject": "暂无",
"planStatus": "暂无"
}
]
}
]
},
"success": true,
"msg": ""
}
还是一样的先用GSONFormat对上述数据生成javaBean格式
这时,在父类下,生成的bean中会有下面的内容:
public static class DataBean {
public int getSaleTarget() {
return SaleTarget;
}
public void setSaleTarget(int SaleTarget) {
this.SaleTarget = SaleTarget;
}
// dataBean中又有:
public List<WeekSalesBean> getWeekSales() {
return weekSales;
}
public void setWeekSales(List<WeekSalesBean> weekSales) {
this.weekSales = weekSales;
}
public List<WeekPlansBean> getWeekPlans() {
return weekPlans;
}
public void setWeekPlans(List<WeekPlansBean> weekPlans) {
this.weekPlans = weekPlans;
}
// weekSalesBean
public static class WeekSalesBean {
private String weekName;
private int saleTotal;
public String getWeekName() {
return weekName;
}
public void setWeekName(String weekName) {
this.weekName = weekName;
}
public int getSaleTotal() {
return saleTotal;
}
public void setSaleTotal(int saleTotal) {
this.saleTotal = saleTotal;
}
}
// weekPansBean
public static class WeekPlansBean {
private String weekName;
// weekPansBean中又有一个数组类型的WeekPlanDetail
private List<WeekPlanDetailBean> weekPlanDetail;
public String getWeekName() {
return weekName;
}
public void setWeekName(String weekName) {
this.weekName = weekName;
}
public List<WeekPlanDetailBean> getWeekPlanDetail() {
return weekPlanDetail;
}
public void setWeekPlanDetail(List<WeekPlanDetailBean> weekPlanDetail) {
this.weekPlanDetail = weekPlanDetail;
}
// WeekPlanDetailBean
public static class WeekPlanDetailBean {
private String planSubject;
private String planStatus;
public String getPlanSubject() {
return planSubject;
}
public void setPlanSubject(String planSubject) {
this.planSubject = planSubject;
}
public String getPlanStatus() {
return planStatus;
}
public void setPlanStatus(String planStatus) {
this.planStatus = planStatus;
}
}
解析:
第一层:因为这里的第一层不再是简单的key,values对
而是有 data Object 类型
因此 要首先
设外层bean为Bean1 数据为zhanDouTaiData
Bean1 bean1 = gson.fromJson(zhanDouTaiData, Bean1.class);
第二层:
bean1.DataBean dataBean = bean1.getData();
// 就可以获取数据了
saleTarget=dataBean.getSaleTarget();
collectionTotal=dataBean.getCollectionTotal();
第三层:
因为data里面还有一个weekSales的数组类型 由上面也可以看出 返回的类型为List<.bean>类型的
// 用一个List<Bean>类型去装载
List<Bean1.DataBean.WeekSalesBean> weekSalesBean = dataBean.getWeekSales();
// 获取每个List中的属性
salesTotal0= weekSalesBean.get(0).getSaleTotal();
salesTotal1= weekSalesBean.get(1).getSaleTotal();
salesTotal2= weekSalesBean.get(2).getSaleTotal();
salesTotal3= weekSalesBean.get(3).getSaleTotal();
salesTotal4= weekSalesBean.get(4).getSaleTotal();
salesTotal5= weekSalesBean.get(5).getSaleTotal();
salesTotal6= weekSalesBean.get(6).getSaleTotal();
List<Bean1.DataBean.WeekPlansBean> weekPlansBeans = dataBean.getWeekPlans();
weekPlansBeans.get(0).getWeekName();
// 同上
第四层: 在WeekPlansBean中 又有一个 数组类型的 其实原理和上面是一样的
List<Bean1.DataBean.WeekPlansBean> weekPlansBeans = dataBean.getWeekPlans();
//** 获取weekPlansBeans的第0层的数据**
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans0 = weekPlansBeans.get(0).getWeekPlanDetail();
// 再将weekPlanDetail第0层的数据的PlanSubject和PlanStatus数据获取
planSubject0.setText(weekPlanDetailBeans0.get(0).getPlanSubject());
planStatus0.setText(weekPlanDetailBeans0.get(0).getPlanStatus());
// 获取weekPlansBeans的第1层的数据
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans1 = weekPlansBeans.get(1).getWeekPlanDetail();
// 再将weekPlanDetail第0层的数据的PlanSubject和PlanStatus数据获取
planSubject1.setText(weekPlanDetailBeans1.get(0).getPlanSubject());
planStatus1.setText(weekPlanDetailBeans1.get(0).getPlanStatus());
// 同上
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans2 = weekPlansBeans.get(2).getWeekPlanDetail();
planSubject2.setText(weekPlanDetailBeans2.get(0).getPlanSubject());
planStatus2.setText(weekPlanDetailBeans2.get(0).getPlanStatus());
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans3 = weekPlansBeans.get(3).getWeekPlanDetail();
planSubject3.setText(weekPlanDetailBeans3.get(0).getPlanSubject());
planStatus3.setText(weekPlanDetailBeans3.get(0).getPlanStatus());
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans4 = weekPlansBeans.get(4).getWeekPlanDetail();
planSubject4.setText(weekPlanDetailBeans4.get(0).getPlanSubject());
planStatus4.setText(weekPlanDetailBeans4.get(0).getPlanStatus());
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans5 = weekPlansBeans.get(5).getWeekPlanDetail();
planSubject5.setText(weekPlanDetailBeans5.get(0).getPlanSubject());
planStatus5.setText(weekPlanDetailBeans5.get(0).getPlanStatus());
List<Bean1.DataBean.WeekPlansBean.WeekPlanDetailBean> weekPlanDetailBeans6 = weekPlansBeans.get(6).getWeekPlanDetail();
planSubject6.setText(weekPlanDetailBeans6.get(0).getPlanSubject());
planStatus6.setText(weekPlanDetailBeans6.get(0).getPlanStatus());
GSON解析 第一层为数组形式的JSON数据
如:
[
{
"pkey": 1,
"cities": [
{
"pkey": 106,
"name": "揭阳"
},
{
"pkey": 308,
"name": "梅州"
}
],
"name": "广东"
},
{
"pkey": 2,
"cities": [
{
"pkey": 1452,
"name": "北京"
}
],
"name": "北京"
},
{
"pkey": 45,
"cities": [
{
"pkey": 1560,
"name": "拉萨"
}
],
"name": "西藏"
}
]
首先也是用 GSONFormat创建Bean类
这里不展示
**解析: **
// 解析 数据
Gson gson = new Gson();
List<ProvinceCityBean> provinceCityBean = gson.fromJson(stringBuilder.toString(),
new TypeToken<List<ProvinceCityBean>>(){}.getType());
List<String> citiesList = new ArrayList<>();
for(int i=0; i<provinceCityBean.size();i++){
options1Items.add(provinceCityBean.get(i).getName());
List<ProvinceCityBean.CitiesBean> citiesBean = provinceCityBean.get(i).getCities();
for(int j=0;j<citiesBean.size();j++) {
// 市
citiesList.add(citiesBean.get(j).getName());
}
}
GSON的序列化
@SerializedName
比如你的json数据为
int a
string b
可以通过序列化将名字更改 方便使用
1 首先,Bean类继承接口
implements Serializable
2 序列化
@SerializedName("a") public int number;
@SerializedName("b") public String userName;
就可以通过number,和userName去使用了