一.Gson解析配置

Android Studio中配置

implementation 'com.google.code.gson:gson:2.8.6'

Gson GitHub链接

https://github.com/google/gson

二.获取Gson对象

1.通过构造函数来获取

Gson gson = new Gson();

2.通过 GsonBuilder 来获取,可以进行多项特殊配置

Gson gson = new GsonBuilder().create();

三.具体使用之  Json字符串转换成JavaBean

数据源

{"age":"14","name":"张三","sex":"男"}

方法使用

gson.fromJson(strings, People.class);

注意:GSON的fromJson共有七个重载方法 如下

android Gson使用 android gson解析_android Gson使用

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    private String strings = "{\"age\":\"14\",\"name\":\"张三\",\"sex\":\"男\"}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        Gson gson = new Gson();
        People people = gson.fromJson(strings, People.class);
        String name = people.getName();
        String sex = people.getSex();
        String age = people.getAge();
        Log.d("TAG", "name----:" + name);
        Log.d("TAG", "sex----:" + sex);
        Log.d("TAG", "age----:" + age);
    }
}

结果

D/TAG: name----:张三
D/TAG: sex----:男
D/TAG: age----:14

说明

fromJson方法可以将Json字符串转换成JavaBean,但是要解析的JavaBean的属性必须是Json字符串中的字段,可以少于Json字符串中的字段。

比如

数据源不变

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    private String strings = "{\"age\":\"14\",\"name\":\"张三\",\"sex\":\"男\"}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        Gson gson = new Gson();
        People people = gson.fromJson(strings, People.class);
        String name = people.getName();
        String age = people.getAge();
        Log.d("TAG", "name----:" + name);
        Log.d("TAG", "age----:" + age);
    }
}

JavaBean

package com.wjn.viewlistdemo;

public class People {

    private String name;
    private String age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

即数据源有三个字段,JavaBean只有两个字段。

结果

D/TAG: name----:张三
D/TAG: age----:14

如果JavaBean中有数据源中没有的字段,那么此字段会返回null。

数据源不变

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    private String strings = "{\"age\":\"14\",\"name\":\"张三\",\"sex\":\"男\"}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        Gson gson = new Gson();
        People people = gson.fromJson(strings, People.class);
        String name = people.getName();
        String sex = people.getSex();
        String age = people.getAge();
        String height = people.getHeight();
        Log.d("TAG", "name----:" + name);
        Log.d("TAG", "sex----:" + sex);
        Log.d("TAG", "age----:" + age);
        Log.d("TAG", "height----:" + height);
    }
}

JavaBean

package com.wjn.viewlistdemo;

public class People {

    private String name;
    private String sex;
    private String age;
    private String height;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }
}

即多了一个height属性。

结果

D/TAG: name----:张三
D/TAG: sex----:男
D/TAG: age----:14
D/TAG: height----:null

Gson解析还要注意大驼峰问题

数据源

{"Age":"14","name":"张三","Sex":"男"}

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    private String strings = "{\"Age\":\"14\",\"name\":\"张三\",\"Sex\":\"男\"}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        Gson gson = new Gson();
        People people = gson.fromJson(strings, People.class);
        String name = people.getName();
        String sex = people.getSex();
        String age = people.getAge();
        Log.d("TAG", "name----:" + name);
        Log.d("TAG", "sex----:" + sex);
        Log.d("TAG", "age----:" + age);
    }
}

结果

D/TAG: name----:张三
D/TAG: sex----:null
D/TAG: age----:null

说明

使用Gson解析数据时数据源Key首字母大写时,要注意。

四.具体使用之  Json字符串转换成List

数据源

[{"sex":"男","age":"20","name":"张三"},{"sex":"女","age":"22","name":"小华"},{"sex":"男","age":"25","name":"李四"},{"sex":"女","age":"27","name":"小丽"}]

方法使用

Type type = new TypeToken<List<People>>() {}.getType();
 List<People> list = gson.fromJson(strings, type);

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

import java.lang.reflect.Type;
import java.util.List;

public class DataStructureActivity extends AppCompatActivity {

    private String strings = "[{\"sex\":\"男\",\"age\":\"20\",\"name\":\"张三\"},{\"sex\":\"女\",\"age\":\"22\",\"name\":\"小华\"},{\"sex\":\"男\",\"age\":\"25\",\"name\":\"李四\"},{\"sex\":\"女\",\"age\":\"27\",\"name\":\"小丽\"}]";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        Gson gson = new Gson();
        Type type = new TypeToken<List<People>>() {
        }.getType();
        List<People> list = gson.fromJson(strings, type);
        for (int i = 0; i < list.size(); i++) {
            People people = list.get(i);
            String name = people.getName();
            String age = people.getAge();
            String sex = people.getSex();
            Log.d("TAG", "name----:" + name);
            Log.d("TAG", "age----:" + age);
            Log.d("TAG", "sex----:" + sex);
        }
    }
}

图解 Type使用具体那个包

android Gson使用 android gson解析_android Gson使用_02

结果

D/TAG: name----:张三
D/TAG: age----:20
D/TAG: sex----:男

D/TAG: name----:小华
D/TAG: age----:22
D/TAG: sex----:女

D/TAG: name----:李四
D/TAG: age----:25
D/TAG: sex----:男

D/TAG: name----:小丽
D/TAG: age----:27
D/TAG: sex----:女

五.具体使用之  本地对象生成Json字符串

1.JsonObject使用

图解

android Gson使用 android gson解析_android Gson使用_03

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.JsonObject;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("name", "张三");
        jsonObject.addProperty("age", 23);
        jsonObject.addProperty("price", 22.9);
        jsonObject.addProperty("isstudent", true);
        String result = jsonObject.toString();
        Log.d("TAG", "result----:" + result);
    }
}

结果

D/TAG: result----:{"name":"张三","age":23,"price":22.9,"isstudent":true}

2.JsonArray使用

图解

android Gson使用 android gson解析_Android Gson_04

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.JsonArray;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        JsonArray jsonArray = new JsonArray();
        jsonArray.add("字符串");
        jsonArray.add(false);
        jsonArray.add('c');
        String result = jsonArray.toString();
        Log.d("TAG", "result----:" + result);
    }
}

结果

D/TAG: result----:["字符串",false,"c"]

说明

addProperty 方法底层调用的是 add(String property, JsonElement value) 方法,即将基本数据类型转化为了 JsonElement 对象,JsonElement 是一个抽象类,而 JsonObject 继承了 JsonElement ,因此我们可以通过 JsonObject 自己来构建一个 JsonElement

Gson的JsonObject和JsonArray都有方法

android Gson使用 android gson解析_Android Gson_05

3.toJson使用

图解

android Gson使用 android gson解析_Android Gson_06

使用第一个重载的方法将Java Bean转换成字符串

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

public class DataStructureActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        People people = new People();
        people.setName("张三");
        people.setAge("14");
        people.setSex("男");
        Gson gson = new Gson();
        String result = gson.toJson(people);
        Log.d("TAG", "result----:" + result);
    }
}

结果

D/TAG: result----:{"age":"14","name":"张三","sex":"男"}

使用第一个重载的方法将List<Java Bean>转换成字符串

代码

package com.wjn.viewlistdemo.activity.datastructure;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.google.gson.Gson;
import com.wjn.viewlistdemo.People;
import com.wjn.viewlistdemo.R;

import java.util.ArrayList;
import java.util.List;

public class DataStructureActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_datastructure);
        testMethod();
    }

    private void testMethod() {
        People people1 = new People();
        people1.setName("张三");
        people1.setAge("14");
        people1.setSex("男");

        People people2 = new People();
        people2.setName("李四");
        people2.setAge("25");
        people2.setSex("男");

        People people3 = new People();
        people3.setName("张华");
        people3.setAge("30");
        people3.setSex("女");

        List<People> list = new ArrayList<>();
        list.add(people1);
        list.add(people2);
        list.add(people3);

        Gson gson = new Gson();
        String result = gson.toJson(list);
        Log.d("TAG", "result----:" + result);
    }
}

结果

D/TAG: result----:[{"age":"14","name":"张三","sex":"男"},{"age":"25","name":"李四","sex":"男"},{"age":"30","name":"张华","sex":"女"}]

六.终极封装工具类

/**
 * Json帮助类
 *
 * @author wujianning
 */
public class JsonHelperUtils {

    /**
     * Json字符串转JavaBean
     *
     * @param json 报文
     * @param cls  目标Bean
     * @return 目标Bean
     */

    public static <T> T fromJson2Bean(String json, Class<T> cls) {
        if (TextUtils.isEmpty(json) || null == cls) return null;
        T t = null;
        try {
            t = new Gson().fromJson(json, cls);
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * Json转List
     *
     * @param json 报文
     * @param cls  目标List存储的Bean
     * @return 目标List
     */

    public static <T> List<T> fromJson2List(String json, Class<T> cls) {
        if (TextUtils.isEmpty(json) || null == cls) return null;
        List<T> list = new ArrayList<>();
        try {
            Gson gson = new Gson();
            JsonArray jsonArray = JsonParser.parseString(json).getAsJsonArray();
            for (JsonElement jsonElement : jsonArray) {
                list.add(gson.fromJson(jsonElement, cls));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * Object(JavaBean或者List)转Json
     *
     * @param obj Object
     * @return 字符串
     */

    public static String fromObject2Json(Object obj) {
        if (null == obj) return "";
        String result = null;
        try {
            result = new Gson().toJson(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}