数据解析之JSON

数据解析之JSON

数据结构

  • Object (对象,在花括号中)
    object
  • Array (数组,在方括号中)
    array

基本类型

  • String 字符串(在双引号中)
  • number 数字(整数或浮点数)
  • 逻辑值 (true,false)
  • null 数据为空

示例

[{
    "name":"张三",
    "age":23,
    "birthday":"1994-01-01",
    "school":"蓝翔",
    "major":[
    "理发",
    "挖掘机"
    ],
    "married":false,
    "car":"大众"},
{
    "name":"小红",
    "age":20,
    "birthday":"1996-01-01",
    "school":"清华",
    "major":[
    "理发",
    "化妆"
    ],
    "married":true,
    "car":null}
]

Json解析的三种方法

根据Json信息建立javaBean类

public class People {
    private String name;
    private int age;
    private String birthday;
    private String school;
    private List<String> major;
    private boolean married;
    private String car;

    getter and setter methods...

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday='" + birthday + '\'' +
                ", school='" + school + '\'' +
                ", major=" + major +
                ", married=" + married +
                ", car='" + car + '\'' +
                '}';
    }

}

1.使用JSONObject

1.1使用getXXX()方法

代码不会去判断是否存在该字段,需要你自己去判断,否则的话会报错。自己判断的话使用has(String name)来判断

private void parseJsonWithJSONObject(String jsonStr) {
    try {
        //peopleList用于存储所有People信息
        List<People> peopleList=new ArrayList<>();
        //获取的json字符串是一个JSONArray对象,其他数据结构还有JSONObject
        JSONArray root=new JSONArray(jsonStr);
        //遍历JSONArray中的JSONObject对象
        for (int i = 0; i < root.length(); i++) {
            //新建people对象,存储解析后的people信息
            People people=new People();
            JSONObject obj = (JSONObject) root.get(i);
            //解析当前JSONObject包含的信息
            String name=obj.getString("name");
            int age=obj.getInt("age");
            String birthday=obj.getString("birthday");
            String school=obj.getString("school");
            JSONArray major=obj.getJSONArray("major");
            List<String> majors=new ArrayList<>();
            //major是一个JSONArray,对其执行遍历
            for (int j = 0; j <major.length() ; j++) {
                String item= (String) major.get(j);
                majors.add(item);
            }
            boolean married=obj.getBoolean("married");
            String car=obj.getString("car");
            people.setName(name);
            people.setAge(age);
            people.setBirthday(birthday);
            people.setSchool(school);
            people.setMajor(majors);
            people.setMarried(married);
            people.setCar(car);

            peopleList.add(people);
            Log.e(TAG, "parseJson: "+people.toString() );
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}
1.2使用optXXX()方法

这些方法在解析时,如果对应字段不存在会返回空值或者0,不会报错

private void parseJsonWithJSONObject2(String jsonStr) {
    try {
        JSONArray root=new JSONArray(jsonStr);
        for (int i = 0; i < root.length(); i++) {
            People people=new People();
            JSONObject obj=root.getJSONObject(i);
            people.setName(obj.optString("name"));
            people.setAge(obj.optInt("age"));
            people.setBirthday(obj.optString("birthday"));
            people.setSchool(obj.optString("school"));
            JSONArray majors=obj.optJSONArray("major");
            List<String> majorList=new ArrayList<>();
            for (int j = 0; j <majors.length() ; j++) {
                majorList.add(majors.optString(j));
            }
            people.setMajor(majorList);
            people.setMarried(obj.optBoolean("married"));
            people.setCar(obj.optString("car"));
            Log.e(TAG, "parseJson2: "+people.toString() );

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

2.使用Gson(简单方便)

需要添加依赖

compile 'com.google.code.gson:gson:2.8.1'

方法:

private void parseJsonWithGson(String jsonStr) {
    Gson gson=new Gson();

    //若解析的是JSONObject对象,很简单,可以这样
    //WeatherResponse response=gson.fromJson(jsonStr,WeatherResponse.class);

    //解析的是Json数组,需要借助TypeToken将期望解析成的数据类型传入到fromJson()方法中
    List<People> response=gson.fromJson(jsonStr,new TypeToken<List<People>>(){}.getType());
    Log.e(TAG, "parseJsonWithGson: "+response.toString() );
}

另外:通过GsonFormat可以快速生成bean类,只需要将要解析的json流拖到框中
GsonFormat

GsonFormat是一个插件,需在在File>Settings>Plugins中勾选
addGsonFormat

Gson支持Date类型,在定义bean类时,对日期可定义为Data类型

//bean类
private Date birthday;

//解析
Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
...
//解析结果:
birthday=Sat Jan 01 00:00:00 GMT+08:00 1994
//在toString()中执行birthday.toLocaleString()显示如下:
birthday=1994年1月1日 00:00:00

3.使用JsonReader

private void parseJsonWithJsonReader(String jsonStr) {
    JsonReader reader = new JsonReader(new StringReader(jsonStr));
    try {
        // 遇到[,开始解析数组
        reader.beginArray();
        List<People> peopleList = new ArrayList<>();
        while (reader.hasNext()) {
            // 遇到{,开始解析对象
            reader.beginObject();
            People people = new People();
            // 新建major集合
            List<String> majors = new ArrayList<>();
            while (reader.hasNext()) {
                String tag = reader.nextName();
                if ("name".equals(tag)) {
                    people.setName(reader.nextString());
                }
                if ("age".equals(tag)) {
                    people.setAge(reader.nextInt());
                }
                if ("birthday".equals(tag)) {
                    people.setBirthday(reader.nextString());
                }
                if ("school".equals(tag)) {
                    people.setSchool(reader.nextString());
                }
                if ("major".equals(tag)) {
                    // 遇到[,开始解析数组
                    reader.beginArray();
                    while (reader.hasNext()) {
                        majors.add(reader.nextString());
                    }
                    // 遇到],数组解析结束
                    reader.endArray();
                    people.setMajor(majors);
                }
                if ("married".equals(tag)) {
                    people.setMarried(reader.nextBoolean());
                }
                if ("car".equals(tag)) {
                    //值类型为null时会报错
                    reader.skipValue();
                }

            }
            // 遇到},对象解析结束
            reader.endObject();
            peopleList.add(people);
        }
        // 遇到],数组解析结束
        reader.endArray();
        Log.e(TAG, "parseJsonReader: " + peopleList.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值