Gson生成json的几种方法

引用gson

1
2
3
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}

Click and drag to move

方法一:Map对象转json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public void printJson1() {
Map<String, Object> student = new HashMap<>();
student.put("name", "野猿新一");
student.put("age", 28);
student.put("emails", new String[]{"yeyuanxinyi@sina.com", "yeyuanxinyi@sohu.com", "yeyuanxinyi@163.com"});

Map<String, Object> girlfriend = new HashMap<>();
girlfriend.put("name", "野援新二");
girlfriend.put("age", 18);
student.put("girlfriend", girlfriend);

String json = new Gson().toJson(student);
Log.d("json", json);
}

Click and drag to move

方法二:Java对象转json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 首先定义一个Java类Student
public class Student {
public String name;
public int age;
public String[] emails;
public Student girlfriend;

public Student(String name, int age) {
this.name = name;
this.age = age;
}
}

public void printJson2() {
Student student = new Student("野猿新一", 28);
student.emails = new String[]{"yeyuanxinyi@sina.com", "yeyuanxinyi@sohu.com", "yeyuanxinyi@163.com"};
student.girlfriend = new Student("野援新二", 18);

String json = new Gson().toJson(student);
Log.d("json", json);
}

Click and drag to move

生成的json结果

以上代码生成的json结果是一样的,如下

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"age": 28,
"emails": [
"yeyuanxinyi@sina.com",
"yeyuanxinyi@sohu.com",
"yeyuanxinyi@163.com"
],
"girlfriend": {
"age": 18,
"name": "野援新二"
},
"name": "野猿新一"
}

Click and drag to move

总结

  • json内容少建议直接用Map生成,省去还要创建一个Java类的步骤。
  • json内容多,层级复杂,建议用Java对象生成,代码结构比较清晰。