1、创建实体类学生:
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 + "]";
}
}
2、解析:
public class DemoParser {
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);
}
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);
}
private static void parserPoint(){
// json 节点解析
String json = "{'flag':true,'data':{'name':'张三','age':18,'sex':true}}";
// 1.获得 解析者
JsonParser parser = new JsonParser();
// 2.获得 根节点元素
JsonElement element = parser.parse(json);
// 3.根据 文档判断根节点属于 什么类型的 Gson节点对象
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);
}
public static void main(String[] args) {
// parser2Object();
// parser2List();
// parser2Map();
parserPoint();
}
}
3、将对象解析为字符串
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);
}
}