现在手上负责的一个项目,有一个配置信息使用的是json来配置的,解析方式为gson。就发一点时间写了一个demo。
gson
gson 是google发布的一个解析json的解析框架
gson github网站:
https://github.com/google/gson
jar包的下载地址:https://mvnrepository.com/artifact/com.google.code.gson/gson
Gson基本用法
toJson序列化.
public String toJson(Object src) {
public String toJson(Object src, Type typeOfSrc) {}
public void toJson(Object src, Appendable writer) throws JsonIOException {}
public void toJson(Object src, Type typeOfSrc, Appendable writer) throws JsonIOException {}
public void toJson(Object src, Type typeOfSrc, JsonWriter writer) throws JsonIOException {}
public String toJson(JsonElement jsonElement) {}
public void toJson(JsonElement jsonElement, Appendable writer) throws JsonIOException {}
public void toJson(JsonElement jsonElement, JsonWriter writer) throws JsonIOException {}
fromJson反序列化.
public <T> T fromJson(String json, Class<T> classOfT) throws JsonSyntaxException {}
public <T> T fromJson(String json, Type typeOfT) throws JsonSyntaxException {}
public <T> T fromJson(Reader json, Class<T> classOfT) throws JsonSyntaxException, JsonIOException {}
public <T> T fromJson(Reader json, Type typeOfT) throws JsonIOException, JsonSyntaxException {}
public <T> T fromJson(JsonReader reader, Type typeOfT) throws JsonIOException, JsonSyntaxException {}
public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {}
public <T> T fromJson(JsonElement json, Type typeOfT) throws JsonSyntaxException {}
Demo
我是使用AndroidStudio来做的此demo
(1)先在assets目录中准备二个文件(test.json,test_list.json),这里要注意一下assets目录的位置,如果不注意会导致读取不到assets目录下的json文件。
test.json
[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
}
]
test_list.json
[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
},
{
"name":"Ketty",
"age":23,
"booleanKey":false,
"school":"K-school",
"address":{"province":"广东","city":"深圳"}
},
{
"name":"John",
"age":15,
"booleanKey":true,
"school":"J-school",
"address":{"province":"广东","city":"广州"}
}
]
(2)准备二个解析支持类
Address.java
package com.example.firstapp;
public class Address {
private String province;
private String city;
public void setCity(String city) {
this.city = city;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public String getProvince() {
return province;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\"province\": ").append(province).append(", \"city\": ").append(city).append('\n');
return sb.toString();
}
}
Student.java
package com.example.firstapp;
public class Student {
private String name;
private int age;
private String school;
private boolean booleanKey;
private Address address;
public void setAge(int age) {
this.age = age;
}
public void setAddress(Address address) {
this.address = address;
}
public void setName(String name) {
this.name = name;
}
public void setSchool(String school) {
this.school = school;
}
public Address getAddress() {
return address;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getSchool() {
return school;
}
public void setBooleanKey(boolean booleanKey) {
this.booleanKey = booleanKey;
}
public boolean getBooleanKey() {
return booleanKey;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("\"name\": ").append(name).append(",\n")
.append("\"age\": ").append(age).append(",\n")
.append("\"booleanKey\": ").append(booleanKey).append(",\n")
.append("\"school\": ").append(school).append(",\n")
.append("\"address\": ").append(address).append('\n');
return sb.toString();
}
}
(3)导入gson包
app\build.gradle
dependencies {
......
implementation 'com.google.code.gson:gson:2.8.6'
}
(4)封闭一个帮忙类GsonHelper.java
package com.example.firstapp;
import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class GsonHelper {
private static Gson mGson = new Gson();
private final static String TAG = "GsonHelper";
public static Object stringToObject(String json, Class classOfT){
return mGson.fromJson(json , classOfT ) ;
}
public static <T> String objectToString(T object) {
return mGson.toJson(object);
}
public static <T> List<T> stringToList(String json,Class<T> cls){
List<T> list = new ArrayList<T>();
JsonArray array = new JsonParser().parse(json).getAsJsonArray();
for(final JsonElement elem : array){
list.add(mGson.fromJson(elem, cls));
}
return list ;
}
public static <T> List<T> string2List(String json,Class<T> cls){
TypeToken<List<T>> typeToken =
new TypeToken<List<T>>() {
};
List<T> list = mGson.fromJson(json, typeToken.getType());
return list ;
}
public static String getAssetsJson(Context context,String jsonFile){
StringBuilder sb = new StringBuilder();
InputStream inputStream = null;
try {
inputStream = context.getResources().getAssets().open(jsonFile);
Log.i(TAG,"inputStream:"+inputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
Log.e(TAG,"e.printStackTrace():"+e.toString());
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static String getJSONString(String path){
StringBuilder sb = new StringBuilder();
File file = new File(path);
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
Log.i(TAG,"inputStream:"+inputStream);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
Log.e(TAG,"e.printStackTrace():"+e.toString());
e.printStackTrace();
}finally {
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
}
(5)实现gson解析json的核心方法
package com.example.firstapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity ";
private final String jsonFile1 = "test.json";
private final String jsonFile2 = "test_list.json";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
Address address = new Address();
address.setCity("city_01");
address.setProvince("province_01");
Student student = new Student();
student.setAddress(address);
student.setAge(10);
student.setName("name_01");
student.setSchool("school_01");
Log.i(TAG,"GsonHelper.objectToString(address):" + GsonHelper.objectToString(address));
Log.i(TAG,"GsonHelper.objectToString(student):" + GsonHelper.objectToString(student));
Log.i(TAG,"=========================01====================================");
Address addressTrans = (Address) GsonHelper.stringToObject(GsonHelper.objectToString(address),Address.class);
Log.i(TAG,"addressTrans:" + addressTrans);
Student studentTrans = (Student) GsonHelper.stringToObject(GsonHelper.objectToString(student),Student.class);
Log.i(TAG,"studentTrans:" + studentTrans);
Log.i(TAG,"==========================02===================================");
ArrayList<Student> arrayList;
Log.i(TAG,"GsonHelper.getAssetsJson(this,jsonFile1):" + GsonHelper.getAssetsJson(this,jsonFile1));
arrayList = (ArrayList)GsonHelper.string2List(GsonHelper.getAssetsJson(this,jsonFile1),Student.class);
for (int i = 0;i < arrayList.size();i++){
Log.i(TAG,"arrayList.get(i):" + arrayList.get(i));
}
Log.i(TAG,"===========================03==================================");
Log.i(TAG,"GsonHelper.getAssetsJson(this,jsonFile2):" + GsonHelper.getAssetsJson(this,jsonFile2));
arrayList = (ArrayList)GsonHelper.string2List(GsonHelper.getAssetsJson(this,jsonFile2),Student.class);
for (int i = 0;i < arrayList.size();i++){
Log.i(TAG,"arrayList.get(i):" + arrayList.get(i));
}
Log.i(TAG,"===========================04==================================");
Log.i(TAG,"GsonHelper.getAssetsJson(this,jsonFile1):" + GsonHelper.getAssetsJson(this,jsonFile1));
arrayList = (ArrayList)GsonHelper.stringToList(GsonHelper.getAssetsJson(this,jsonFile1),Student.class);
for (int i = 0;i < arrayList.size();i++){
Log.i(TAG,"arrayList.get(i):" + arrayList.get(i));
}
Log.i(TAG,"===========================05==================================");
Log.i(TAG,"GsonHelper.getAssetsJson(this,jsonFile2):" + GsonHelper.getAssetsJson(this,jsonFile2));
arrayList = (ArrayList)GsonHelper.stringToList(GsonHelper.getAssetsJson(this,jsonFile2),Student.class);
for (int i = 0;i < arrayList.size();i++){
Log.i(TAG,"arrayList.get(i):" + arrayList.get(i));
}
}
}
输出测试结果:
I/MainActivity: GsonHelper.objectToString(address):{"city":"city_01","province":"province_01"}
I/MainActivity: GsonHelper.objectToString(student):{"address":{"city":"city_01","province":"province_01"},"age":10,"booleanKey":false,"name":"name_01","school":"school_01"}
I/MainActivity: =========================01====================================
addressTrans:"province": province_01, "city": city_01
studentTrans:"name": name_01,
"age": 10,
"booleanKey": false,
"school": school_01,
"address": "province": province_01, "city": city_01
I/MainActivity: ==========================02===================================
GsonHelper.getAssetsJson(this,jsonFile1):[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
}
]
I/MainActivity: arrayList.get(i):{name=Tom, age=13.0, booleanKey=true, school=T-school, address={province=广东, city=惠州}}
I/MainActivity: ===========================03==================================
GsonHelper.getAssetsJson(this,jsonFile2):[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
},
{
"name":"Ketty",
"age":23,
"booleanKey":false,
"school":"K-school",
"address":{"province":"广东","city":"深圳"}
},
{
"name":"John",
"age":15,
"booleanKey":true,
"school":"J-school",
"address":{"province":"广东","city":"广州"}
}
]
I/MainActivity: arrayList.get(i):{name=Tom, age=13.0, booleanKey=true, school=T-school, address={province=广东, city=惠州}}
I/MainActivity: arrayList.get(i):{name=Ketty, age=23.0, booleanKey=false, school=K-school, address={province=广东, city=深圳}}
I/MainActivity: arrayList.get(i):{name=John, age=15.0, booleanKey=true, school=J-school, address={province=广东, city=广州}}
I/MainActivity: ===========================04==================================
GsonHelper.getAssetsJson(this,jsonFile1):[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
}
]
arrayList.get(i):"name": Tom,
"age": 13,
"booleanKey": true,
"school": T-school,
"address": "province": 广东, "city": 惠州
I/MainActivity: ===========================05==================================
GsonHelper.getAssetsJson(this,jsonFile2):[
{
"name":"Tom",
"age":13,
"booleanKey":true,
"school":"T-school",
"address":{"province":"广东","city":"惠州"}
},
{
"name":"Ketty",
"age":23,
"booleanKey":false,
"school":"K-school",
"address":{"province":"广东","city":"深圳"}
},
{
"name":"John",
"age":15,
"booleanKey":true,
"school":"J-school",
"address":{"province":"广东","city":"广州"}
}
]
I/MainActivity: arrayList.get(i):"name": Tom,
"age": 13,
"booleanKey": true,
"school": T-school,
"address": "province": 广东, "city": 惠州
I/MainActivity: arrayList.get(i):"name": Ketty,
"age": 23,
"booleanKey": false,
"school": K-school,
"address": "province": 广东, "city": 深圳
I/MainActivity: arrayList.get(i):"name": John,
"age": 15,
"booleanKey": true,
"school": J-school,
"address": "province": 广东, "city": 广州
关于getJSONString接口
我只说我验证OK的一个接口:
private final String pathJSON = "/sdcard/test_list.json";
private void parseJsonWithPath() {
Log.i(TAG,"==============00======================");
File file = new File(pathJSON);
Log.i(TAG,"file.getAbsolutePath():" + file.getAbsolutePath());
Log.i(TAG,"file.exists():" + file.exists());
Log.i(TAG,"=========01==============");
Log.i(TAG,"GsonHelper.getJSONString(pathJSON):" + GsonHelper.getJSONString(pathJSON));
此接口注意,需要是内置有手机中的应用,并且权限要高,要不然执行会报各种权限错误。
参考资料
Android Gson的使用总结
https://www.cnblogs.com/zhaoyanjun/p/5842601.html
浅谈Android项目----JSON解析(4种解析技术详解)
https://www.cnblogs.com/chengmuzhe/p/10596922.html
Android项目之JSON解析(3种解析技术详解)
https://blog.csdn.net/mp624183768/article/details/79714085
android gson的使用
https://www.jianshu.com/p/6016be95d4f9