Gson的使用
今天简单的介绍一下Gson的用法:
student类:
public class Student {
private String name;
private int age;
private boolean sex;
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;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean gender) {
this.sex = gender;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", sex=" + sex + "]";
}
}
将java对象转换成json格式
public class DemoFormat {
// java代码转换成json对象
public static void main(String[] args) {
Student stu = new Student();
stu.setName("张三");
stu.setAge(18);
stu.setSex(true);
Gson gson = new Gson();
String json = gson.toJson(stu);
System.out.println(json);
}
}
将json准换成对象
private static void parser2Object() {
// json转换成对象
String json = "{'name':'张三','age':18,'sex':true}";
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
System.out.println(student);
}
将json转换成List集合或者Map集合
private static void parser2Map() {
String json = "{'С3':{'name':'С3','age':20,'sex':true},'С4':{'name':'С4','age':21,'sex':false},'С5':{'name':'С5','age':22,'sex':true},'С1':{'name':'С1','age':18,'sex':true},'С2':{'name':'С2','age':19,'sex':false}}";
Gson gson = new Gson();
TypeToken<Map<String, Student>> token = new com.google.gson.reflect.TypeToken<Map<String, Student>>() {
};
Map<String, Student> stus = gson.fromJson(json, token.getType());
System.out.println(stus);
}
private static void parser2list() {
String json = "[{'name':'С1','age':18,'sex':true},{'name':'С2','age':19,'sex':false},{'name':'С3','age':20,'sex':true},{'name':'С4','age':21,'sex':false},{'name':'С5','age':22,'sex':true}]";
Gson gson = new Gson();
TypeToken<List<Student>> token = new com.google.gson.reflect.TypeToken<List<Student>>() {};
List<Student> stus = gson.fromJson(json, token.getType());
System.out.println(stus);
}
json节点的解析
//json的节点解析
String json = "{'flag':true,'data':{'name':'张三','age':18,'sex':true}}";
//1、获得解析者
JsonParser parser = new JsonParser();
//2、拿到json对象的根节点
JsonElement element = parser.parse(json);
//3、拿到json对象的根节点
JsonObject root = element.getAsJsonObject();
//4、取得节点下的value值
JsonPrimitive flagJson = root.getAsJsonPrimitive("flag");
boolean flag = flagJson.getAsBoolean();
JsonObject dataJson = root.getAsJsonObject("data");
Student student = new Gson().fromJson(dataJson, Student.class);
System.out.println(flag);
System.out.println(student);