Gson toJson() 用法

示例数据结构定义:

public class Student {

                   public int id;

                   public String nickName;

                   public int age;

                   public ArrayList<String> books;

                   public HashMap<String, String> booksMap;

}

简单数据结构

Student student = new Student();

student.id = 1;

student.nickName = "Jack";

student.age = 22;

student.email = "tr@qq.com";

Gson gson = new Gson();

Log.e("MainActivity", gson.toJson(student));

 

打印输出:

{"email":"tr@qq.com","nickName":" Jack ","id":1,"age":22}

基本数据类型

还包含List集合

Student student = new Student();

student.id = 1;

student.nickName = " Jack ";

student.age = 22;

student.email = "965266509@qq.com";

ArrayList<String> books = new ArrayList<String>();

books.add("数学");

books.add("语文");

books.add("英语");

books.add("物理");

books.add("化学");

books.add("生物");

student.books = books;

Gson gson = new Gson();

Log.e("MainActivity", gson.toJson(student));

 

打印输出:

{"books":["数学","语文","英语","物理","化学","生物"],"email":"965266509@qq.com","nickName":" Jack ","id":1,"age":22}

基本数据类型

还包含了List和Map集合

Student student = new Student();

student.id = 1;

student.nickName = "Jack";

student.age = 22;

student.email = "965266509@qq.com";

ArrayList<String> books = new ArrayList<String>();

books.add("数学");

books.add("语文");

books.add("英语");

books.add("物理");

books.add("化学");

books.add("生物");

student.books = books;

HashMap<String, String> booksMap = new HashMap<String, String>();

booksMap.put("1", "数学");

booksMap.put("2", "语文");

booksMap.put("3", "英语");

booksMap.put("4", "物理");

booksMap.put("5", "化学");

booksMap.put("6", "生物");

student.booksMap = booksMap;

Gson gson = new Gson();

Log.e("MainActivity", gson.toJson(student));

 

打印输出:

{"books":["数学","语文","英语","物理","化学","生物"],"booksMap":{"3":"英语","2":"语文","1":"数学","6":"生物","5":"化学","4":"物理"},"email":"965266509@qq.com","nickName":"Jack","id":1,"age":22}
posted @ 2018-08-23 08:04  Reboost  阅读(8159)  评论(0编辑  收藏  举报