语法
- 1个JSON文件里含多个数据,这些数据 以 JSON值的形式存在
// JSON实例
{
"l1": {
"l1_1": [
"l1_1_1",
"l1_1_2"
],
"l1_2": {
"l1_2_1": 121
}
},
"l2": {
"l2_1": null,
"l2_2": true,
"l2_3": {}
}
}
-
1个JSON值的内容形式可以是:“名称 - 值对”、数组或对象,下面将详细说明
解析方式
- 说明:json的解析方式有很多种(Android自带org.json解析、Gson、Jackson等),这里我选择效率、依赖包最小和健壮性最好的fastjson来进行解析,比竟如果fastjson能最好的满足我们的要求,其它的都将是将就。
具体使用步骤
1、在Android Gradle导入依赖
注意:由于我是android开发者,我这里引入的针对android的fastjson,这样可以减少下载依赖包的大小,把fastjson中一些我们android端不需要的类和方法可以不导入进来。
dependencies {
implementation 'com.alibaba:fastjson:1.1.68.android'
}
2、编写FastJson工具类
import com.alibaba.fastjson.JSON;
import java.util.List;
/**
* FastJson工具类
*/
public class FastJsonUtil {
/**
* json字符串解析成对象
* @param json
* @param clazz
* @param <T>
* @return
*/
public static <T> T json2Object(String json,Class<T> clazz) {
return JSON.parseObject(json,clazz);
}
/**
* json字符串解析成List集合
* @param json
* @param clazz
* @param <T>
* @return
*/
public static <T> List<T> json2List(String json, Class<T> clazz) {
return JSON.parseArray(json, clazz);
}
/**
* 对象转换为json字符串
* @param object
* @return
*/
public static String object2Json(Object object) {
return JSON.toJSONString(object);
}
}
3、创建一个与JSON数据对应的JavaBean类(用作存储需要解析的数据)
-
Gson解析的关键 = 根据JSON数据 写出一个对应的JavaBean,规则是:
- 下面用2个例子说明如何通过JSON文档创建JavaBean类
/*
简单转换
*/
{
"id": 1,
"name": "小明",
"sex": "男",
"age": 18,
"height": 175
}
// 对应的JavaBean类
public class Student {
private int id;
private String name;
private String sex;
private int age;
private int height;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
public void setHeight(int height){
this.height = height;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
public int getHeight(){
return height;
}
}
/*
复杂转换(具备嵌套)
*/
{"translation":["车"],
"basic":
{
"phonetic":"kɑː",
"explains":["n. 汽车;车厢","n. (Car)人名;(土)贾尔;(法、西)卡尔;(塞)察尔"]},
"query":"car",
"errorCode":0,
"web":[{"value":["汽车","车子","小汽车"],"key":"Car"},
{"value":["概念车","概念车","概念汽车"],"key":"concept car"},
{"value":["碰碰车","碰撞用汽车","碰碰汽车"],"key":"bumper car"}]
}
// 对应的复杂数据对应的JavaBean类
public class car {
public String[] translation; //["车"]数组
public basic basic; //basic对象里面嵌套着对象,创建一个basic内部类对象
class basic{ //建立内部类
public String phonetic;
public String[] explains;
}
public String query;
public int errorCode;
public List<wb> web; //web是一个对象数组,创建一个web内部类对象
class wb{
public String[] value;
public String key;
}
}
注:若觉得转换过于复杂,请直接使用工具:JSON字符串在线转Java实体类工具
4、使用FastJson工具类进行解析
School对应的JavaBean类
import java.util.Arrays;
import java.util.List;
/*需解析的JSON数据:school.json
将该文件放入到项目的main\assets文件夹里(没有assets文件夹的话手动创建)
{"student":
[
{"id":1,"name":"小明","sex":"男","age":18,"height":175,"date":[2013,8,11]},
{"id":2,"name":"小红","sex":"女","age":19,"height":165,"date":[2013,8,23]},
{"id":3,"name":"小强","sex":"男","age":20,"height":185,"date":[2013,9,1]}
],
"grade":"2"
}*/
public class School {
private List<stu> student;
private int grade;
public void setStudent(List<stu> student){
this.student = student;
}
public List<stu> getStudent(){
return student;
}
public void setGrade(int grade){
this.grade = grade;
}
public int getGrade(){
return grade;
}
static class stu {
private int id;
private String name;
private String sex;
private int age;
private int height;
private int[] date;
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setSex(String sex){
this.sex = sex;
}
public String getSex(){
return sex;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public void setHeight(int height){
this.height = height;
}
public int getHeight(){
return height;
}
public void setDate(int[] date){
this.date = date;
}
public int[] getDate(){
return date;
}
@Override
public String toString() {
return "stu{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", height=" + height +
", date=" + Arrays.toString(date) +
'}';
}
}
@Override
public String toString() {
return "School{" +
"student=" + student +
", grade=" + grade +
'}';
}
}
具体用工具类进行解析测试代码
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//json2Object
try {
// 1. //从assets获取json文件
InputStreamReader isr = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("assets/" + "school.json"),"utf-8");
BufferedReader bfr = new BufferedReader(isr);
String line;
StringBuilder stringBuilder = new StringBuilder();
while ((line = bfr.readLine())!=null){
stringBuilder.append(line);
}
School school = FastJsonUtil.json2Object(stringBuilder.toString(), School.class);
Log.d("FastJsonUtil",school.toString());
} catch (IOException e) {
e.printStackTrace();
}
//json2List
// 3. 使用Gson解析:将JSON数据转为单个类实体
String json = "[\n" +
" {\"id\":1,\"name\":\"小明\",\"sex\":\"男\",\"age\":18,\"height\":175,\"date\":[2013,8,11]},\n" +
" {\"id\":2,\"name\":\"小红\",\"sex\":\"女\",\"age\":19,\"height\":165,\"date\":[2013,8,23]},\n" +
" {\"id\":3,\"name\":\"小强\",\"sex\":\"男\",\"age\":20,\"height\":185,\"date\":[2013,9,1]}\n" +
"]";
List<School.stu> stuList = FastJsonUtil.json2List(json, School.stu.class);
Log.d("FastJsonUtil",stuList.toString());
//object2Json
List<String> mList = new ArrayList<>();
for (int i = 0; i < 6; i++) {
mList.add("数据"+i);
}
Log.d("FastJsonUtil",FastJsonUtil.object2Json(mList));
}
}
输出日志
FastJsonUtil: School{student=[stu{id=1, name='小明', sex='男', age=18, height=175, date=[2013, 8, 11]}, stu{id=2, name='小红', sex='女', age=19, height=165, date=[2013, 8, 23]}, stu{id=3, name='小强', sex='男', age=20, height=185, date=[2013, 9, 1]}], grade=2}
FastJsonUtil: [stu{id=1, name='小明', sex='男', age=18, height=175, date=[2013, 8, 11]}, stu{id=2, name='小红', sex='女', age=19, height=165, date=[2013, 8, 23]}, stu{id=3, name='小强', sex='男', age=20, height=185, date=[2013, 9, 1]}]
FastJsonUtil: ["数据0","数据1","数据2","数据3","数据4","数据5"]
好了到此为止基本就完了,json解析在实际开发中用的还是挺多的,掌握还是必须的,记不住就收藏点评论下或点个赞哦!