Gson的使用会让json格式解析变的非常简单和高效。
第一步:增加Gson依赖
implementation 'com.solidfire.code.gson:gson:2.6.2'
第二步:安装GsonFormat插件快速解析实体类
安装插件的步骤可以查看https://www.jianshu.com/p/6a389ef8a665
json范例:{students:[{name:‘小名’,age:25},{name:‘阿名’,age:26}],classX:‘大班’}
使用插件解析的实体类
package com.example.lc.mydemo.bean;
import java.util.List;
public class Student {
/**
* students : [{"name":"小名","age":25},{"name":"阿名","age":26}]
* class : 大班
*/
private String classX;
private List<StudentsBean> students;
public String getClassX() {
return classX;
}
public void setClassX(String classX) {
this.classX = classX;
}
public List<StudentsBean> getStudents() {
return students;
}
public void setStudents(List<StudentsBean> students) {
this.students = students;
}
public static class StudentsBean {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
第三步:解析JSON
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String Data = "{students:[{name:'小名',age:25},{name:'阿名',age:26}],classX:'大班'}";
Gson gson = new Gson();
Student b = gson.fromJson(Data,Student.class);
Log.e(TAG, "onCreate: "+b.getClassX());
List<Student.StudentsBean> list=b.getStudents();
int count=list.size();
for(int i=0;i<count;i++){
Log.e(TAG, "onCreate: "+list.get(i).getName());
}
}
解析结果:
E/MainActivity: onCreate: 大班
E/MainActivity: onCreate: 小名
E/MainActivity: onCreate: 阿名