Json

作者: Anwfly | 来源:发表于2020-10-06 11:01 被阅读0次

一、 Json简介

1、什么是Json

Json(JavaScript Object Notation) 是一种轻量级的数据交换格式,相比于xml这种数据交换格式来说,因为解析xml比较的复杂,而且需要编写,所以客户端和服务器的数据交换格式往往通过Json来进行交换。尤其是对于web开发来说,Json数据格式在客户端直接可以通过javascript来进行解析。

2、Json分类

Json分两类:

  1. 数组方式:JsonArray
  2. 对象方式:JsonObject

3、Json格式

  1. 对象方式
    JsonObject是一种以 (key/value)对形式存在的无序的对象,对象以“{”(左花括号)开始,“}”(右花括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。

    {
     "status": 0,
     "msg": "SUCCESS",
     "data": [{
         "id": 1,
         "name": "xiaohong"
     }, {
         "id": 2,
         "name": "xiaoming"
     }]
    }
    
  2. 数组方式
    JsonArray是一种以"[]"形式存放数组对象方式存储无序对象的。

    [{
     "id": 1,
     "name": "xiaoming"
    }, {
     "id": 2,
     "name": "xiaohong"
    }]
    

4、 简单JsonObject 编写实体类★★★★

案例分析:把Json字符串解析成实体类

  1. 创建Json字符串;
  2. 获取JSONObject对象;
  3. 使用JSONObject方法getString获取Json中值。

案例代码:

//json格式字符串
String jsonObjectString = "{"sex": "男","name": "大飞","age": 18}";
//把json字符串转为JsonObject对象
try {
    JSONObject jsonObject = new JSONObject(jsonObjectString);
    //对象获取属性值
    String sex = jsonObject.getString("sex");
    String name = jsonObject.getString("name");
    int age = jsonObject.getInt("age");
    Log.e("TAG", "姓名:" + name + "  年龄:" + age + "  性别:" + sex);
} catch (JSONException e) {
    e.printStackTrace();
}

5、 简单JsonArray 编写实体类★★★★

案例分析:

  1. 获取数据或者创建数据;
  2. 解析数据;
  3. 显示Json数据。

案例代码:

//获取数据或者创建数据
String json ="[{"id": 1,"name": "xiaoming"},{"id": 2,"name": "xiaohong"}]";
List<UserBean> list = new ArrayList<>();
//解析数据
try {
    JSONArray jsonArray = new JSONArray(json);
    //遍历
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject = jsonArray.getJSONObject(i);
        if (jsonObject != null) {
            int id = jsonObject.optInt("id");
            String name = jsonObject.optString("name");
            //封装java对象
            UserBean userBean = new UserBean(id, name);
            list.add(userBean);
        }
    }
} catch (JSONException e) {
    e.printStackTrace();
}

//显示json数据
Log.e("TAG", "原始数据:" + json);
for(int i = 0; i < list.size(); i++) {
    UserBean userBean = list.get(i);
    Log.e("TAG", "解析收数据:姓名:" + userBean.getName()+"编号:"+userBean.getId());
}

二、 Json编写实体类

1、 复杂jsonObject编写实体类(至少三层)

案例分析:复杂对象字符串解析为实体类

  1. Json格式字符串;

  2. 把Json字符串转为JsonObject对象;

    a. 封装java对象;

    b. 对象获取属性值:
    第一层解析、第一层封装;

    ​ 第二层解析、第二层封装;

    ​ 第三层解析、第三层封装。

  3. 打印实体类

案例代码:

//json格式字符串
String json = "{"code": 200,"data": {"count": 3,"items": [{"title": "油焖大虾","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg"},{"title": "四川回锅肉","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg"},{"title": "超简单芒果布丁","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg"}]}}";

try {
    //把json字符串转为JsonObject对象
    JSONObject jsonObject = new JSONObject(json);
    //封装java对象
    FoodBean foodBean = new FoodBean();

    //对象获取属性值
    //第一层解析
    int code = jsonObject.getInt("code");
    JSONObject data = jsonObject.getJSONObject("data");
    //第一层封装
    foodBean.setCode(code);
    FoodBean.DataBean dataBean = new FoodBean.DataBean();
    foodBean.setData(dataBean);

    //第二层解析
    int count = data.getInt("count");
    JSONArray jsonArray = data.getJSONArray("items");
    //第二层封装
    dataBean.setCount(count);
    List<FoodBean.DataBean.ItemsBean> list = new ArrayList<>();
    dataBean.setItems(list);

    //第三层解析
    //遍历取得数组里面所有json对象
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject1 = jsonArray.optJSONObject(i);
        if (jsonObject1 != null) {
            String pic = jsonObject1.getString("pic");
            String title = jsonObject1.getString("title");

            //第三层封装
            FoodBean.DataBean.ItemsBean itemsBean = new FoodBean.DataBean.ItemsBean();
            itemsBean.setPic(pic);
            itemsBean.setTitle(title);
            list.add(itemsBean);
        }
    }

    //打印实体类
    Log.e("TAG", "请求码:" + foodBean.getCode());
    Log.e("TAG", "data数据:\n" );
    for (int i = 0; i < foodBean.getData().getItems().size(); i++) {
        Log.e("TAG", foodBean.getData().getItems().get(i).getTitle());
    }
} catch (JSONException e) {
    e.printStackTrace();
}

2、 复杂jsonArray编写实体类(至少三层)★★★★

案例分析:

  1. Json格式字符串;

  2. 创建集合;

  3. 把Json字符串转为JsonObject对象;

  4. 遍历JsonObject对象;

  5. 封装java对象:

    解析第一层、第一层封装;

    解析第二层、第二层封装;

    解析第三层、第三层封装。

案例代码:

//json格式字符串
String json = "[{"title": "油焖大虾","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg","data": {"type": "food","material": {"liquid": "water"}}},{"title": "四川回锅肉","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg","data": {  "type": "food","material": {"liquid": "water"}}},{"title": "超简单芒果布丁","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg","data": {"type": "food ","material": {"liquid": "water"}}}]";

//创建集合
List<FoodListBean> list = new ArrayList<>();
try {
    //把json字符串转为JsonObject对象
    JSONArray jsonArray = new JSONArray(json);
    //遍历JsonObject对象
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonObject1 = jsonArray.getJSONObject(i);

        //封装java对象
        FoodListBean foodListBean = new FoodListBean();
        if (jsonObject1 != null) {
            //解析第一层
            String pic = jsonObject1.getString("pic");
            String title = jsonObject1.optString("title");
            JSONObject jsonObject2 = jsonObject1.getJSONObject("data");

            //第一层封装
            foodListBean.setPic(pic);
            foodListBean.setTitle(title);
            FoodListBean.DataBean dataBean = new FoodListBean.DataBean();
            foodListBean.setData(dataBean);

            //第二层解析
            String type = jsonObject2.getString("type");
            JSONObject jsonObject3 = jsonObject2.getJSONObject("material");

            //第二层封装
            dataBean.setType(type);
            FoodListBean.DataBean.MaterialBean materialBean = new FoodListBean.DataBean.MaterialBean();
            dataBean.setMaterial(materialBean);

            //第三层解析
            String liquid = jsonObject3.getString("liquid");

            //第三层封装
            materialBean.setLiquid(liquid);

            //添加到集合
            list.add(foodListBean);
        }
    }
    //日志打印实体类
    for (int i = 0; i < list.size(); i++) {
        FoodListBean foodListBean = list.get(i);
        Log.e("TAG1", foodListBean.getTitle() + "的类型是" + foodListBean.getData().getType() + ",他的材质是" + foodListBean.getData().getMaterial().getLiquid());
    }
} catch (JSONException e) {
    e.printStackTrace();
}

三、 Gson使用

概述:Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。

使用:

  1. 添加依赖

    dependencies {
      implementation 'com.google.code.gson:gson:2.8.6'
    }
    
  2. 使用

    //创建gson对象
    Gson gson = new Gson();
    //gson将json转换为实体类
    FoodBean foodBean = gson.fromJson(json, FoodBean.class);
    //gson将实体类转换为json
    FoodBean foodBean = new FoodBean();
    String json = gson.toJson(foodBean);
    

1、 使用Gson将Java对象映射为json对象

案例分析:

  1. 创建bean对象;
  2. 给bean对象赋值;
  3. 获取Gson对象;
  4. 使用Gson将bean转为json;
  5. 打印数据。

案例代码:

private void easyBeanToJsonObject() {
    //创建bean对象
    StudentBean studentBean = new StudentBean();

    //设置bean对象值
    studentBean.setAge(18);
    studentBean.setName("大飞");
    studentBean.setSex("男");

    //获取gson对象
    Gson gson = new Gson();

    //使用gson将bean转为json
    String json = gson.toJson(studentBean);

    //打印json数据
    Log.e("TAG", "简单bean转换为json:" + json);
}

2、使用Gson将java集合映射为jsonArray

案例分析:

  1. 创建集合,存放bean类;
  2. 设置bean对象值;
  3. 创建bean对象;
  4. 添加到集合;
  5. 获取gson对象;
  6. 打印json数据。

案例代码:

private void easyBeanToJsonArray() {
    //创建集合
    ArrayList<StudentBean> list = new ArrayList<>();

    //设置bean对象值
    for (int i = 0; i < 3; i++) {
        //创建bean对象
        StudentBean studentBean = new StudentBean();
        studentBean.setAge(18 + i);
        studentBean.setName("大飞" + i);
        studentBean.setSex("男");
        //添加到集合
        list.add(studentBean);
    }

    //获取gson对象
    Gson gson = new Gson();

    //使用gson将bean转为json
    String json = gson.toJson(list);

    //打印json数据
    Log.e("TAG", "简单bean转换为JsonArray:\n" + json);
}

3、Gson 生成复杂jsonObject(至少三层)★★★★

案例分析:

  1. 创建java实体类;
  2. 封装第三层数据;
  3. 封装第二层数据;
  4. 封装第一层数据;
  5. 创建gson对象;
  6. 使用gson的方法toJson将实体类转换为json;
  7. 打印数据。

案例代码:

private void multiBeanToJsonObject() {
    //创建java实体类
    FoodBean foodBean = new FoodBean();

    //封装第三层数据
    ArrayList<FoodBean.DataBean.ItemsBean> itemsBeans = new ArrayList<>();
    FoodBean.DataBean.ItemsBean itemsBean1 = new FoodBean.DataBean.ItemsBean();
    itemsBean1.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg");
    itemsBean1.setTitle("油焖大虾");
    itemsBeans.add(itemsBean1);

    FoodBean.DataBean.ItemsBean itemsBean2 = new FoodBean.DataBean.ItemsBean();
    itemsBean2.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg");
    itemsBean2.setTitle("四川回锅肉");
    itemsBeans.add(itemsBean2);

    FoodBean.DataBean.ItemsBean itemsBean3 = new FoodBean.DataBean.ItemsBean();
    itemsBean3.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg");
    itemsBean3.setTitle("超简单芒果布丁");
    itemsBeans.add(itemsBean3);

    //封装第二层数据
    FoodBean.DataBean dataBean = new FoodBean.DataBean();
    dataBean.setCount(3);
    dataBean.setItems(itemsBeans);

    //封装第一层数据
    foodBean.setCode(0);
    foodBean.setData(dataBean);

    //创建gson对象
    Gson gson = new Gson();

    //gson将实体类转换为JsonObject
    String json = gson.toJson(foodBean);

    //打印数据
    Log.e("TAG", "\n复杂bean转换为JsonObject:\n" + json);
}

4、 Gson 生成复杂jsonArray(至少三层)★★★★

案例分析:

  1. 创建集合;
  2. 封装java实体类;
  3. 创建gson对象;
  4. gson将实体类转换为JsonArray;
  5. 打印数据。

案例代码:

private void multiBeanToJsonArray() {
    //创建集合
    ArrayList<FoodListBean> list = new ArrayList<>();

    //封装java实体类
    FoodListBean foodListBean1 = new FoodListBean();
    foodListBean1.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg");
    foodListBean1.setTitle("油焖大虾");
    FoodListBean.DataBean dataBean1 = new FoodListBean.DataBean();
    FoodListBean.DataBean.MaterialBean materialBean1 = new FoodListBean.DataBean.MaterialBean();
    materialBean1.setLiquid("water");
    dataBean1.setMaterial(materialBean1);
    dataBean1.setType("food");
    foodListBean1.setData(dataBean1);
    list.add(foodListBean1);

    FoodListBean foodListBean2 = new FoodListBean();
    foodListBean2.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg");
    foodListBean2.setTitle("四川回锅肉");
    FoodListBean.DataBean dataBean2 = new FoodListBean.DataBean();
    FoodListBean.DataBean.MaterialBean materialBean2 = new FoodListBean.DataBean.MaterialBean();
    materialBean2.setLiquid("water");
    dataBean2.setMaterial(materialBean2);
    dataBean2.setType("food");
    foodListBean2.setData(dataBean2);
    list.add(foodListBean2);

    FoodListBean foodListBean3 = new FoodListBean();
    foodListBean3.setPic("http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg");
    foodListBean3.setTitle("超简单芒果布丁");
    FoodListBean.DataBean dataBean3 = new FoodListBean.DataBean();
    FoodListBean.DataBean.MaterialBean materialBean3 = new FoodListBean.DataBean.MaterialBean();
    materialBean3.setLiquid("water");
    dataBean3.setMaterial(materialBean3);
    dataBean3.setType("food");
    foodListBean3.setData(dataBean3);
    list.add(foodListBean3);

    //创建gson对象
    Gson gson = new Gson();

    //gson将实体类转换为JsonArray
    String json = gson.toJson(list);

    //打印数据
    Log.e("TAG", "\n复杂bean转换为JsonArray:\n" + json);
}

5. 使用Gson将Json对象映射为Java对象

Gson gson = new Gson();
//gosn解析对象
WetherBean wetherBean = gson.fromJson(json, WetherBean.class);

6. 使用Gson将Json数组对象映射为Java集合

Gson gson = new Gson();
//json格式字符串
String json = "[{"title": "油焖大虾","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/9/8289.jpg","data": {"type": "food","material": {"liquid": "water"}}},{"title": "四川回锅肉","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg","data": {  "type": "food","material": {"liquid": "water"}}},{"title": "超简单芒果布丁","pic": "http://www.qubaobei.com/ios/cf/uploadfile/132/31/30630.jpg","data": {"type": "food ","material": {"liquid": "water"}}}]";
Type type = new TypeToken<ArrayList<FoodBean>>() {}.getType();
ArrayList<FoodBean> list = gson.fromJson(json, type);

相关文章

网友评论

      本文标题:Json

      本文链接:https://www.haomeiwen.com/subject/bcqtpktx.html