A、Map对象转json
public void printJson1() {
Map<String, Object> student = new HashMap<>();
student.put("name", "张三");
student.put("age", 20);
student.put("emails", new String[]{"shangsan@163.com", "lisi@126.com", "wangwu@sina.com"});
Map<String, Object> girlfriend = new HashMap<>();
girlfriend.put("name", "韩梅梅");
girlfriend.put("age", 18);
student.put("girlfriend", girlfriend);
String json = new Gson().toJson(student);
}
B、Java对象转json
// 首先定义一个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("张三", 20);
student.emails = new String[]{"zhangsan@163.com", "lisi@126.com", "wangwu@sina.com"};
student.girlfriend = new Student("韩梅梅", 18);
String json = new Gson().toJson(student);
}
json内容少建议直接用Map生成,省去还要创建一个Java类的步骤。
json内容多,层级复杂,建议用Java对象生成,代码结构比较清晰。
博客介绍了Map对象和Java对象转JSON的情况。当JSON内容少,可直接用Map生成,省去创建Java类步骤;若JSON内容多、层级复杂,建议用Java对象生成,使代码结构更清晰。
1650

被折叠的 条评论
为什么被折叠?



