欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用GSON库转换Java对象为JSON对象的进阶实例详解

程序员文章站 2024-03-12 22:50:45
对list和map等结构的常用转换操作基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析: [{"tablename"...

对list和map等结构的常用转换操作基本上可以满足我们处理的绝大多数需求,但有时项目中对json有特殊的格式规定.比如下面的json串解析:

[{"tablename":"students","tabledata":[{"id":1,"name":"李坤","birthday":"jun 22, 2012 9:54:49 pm"},{"id":2,"name":"曹贵生","birthday":"jun 22, 2012 9:54:49 pm"},{"id":3,"name":"柳波","birthday":"jun 22, 2012 9:54:49 pm"}]},{"tablename":"teachers","tabledata":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}]

分析之后我们发现普通的方式都不好处理上面的json串.请看本文是如何处理的吧:

实体类:

import java.util.date; 
 
public class student { 
  private int id; 
  private string name; 
  private date birthday; 
 
  public int getid() { 
    return id; 
  } 
 
  public void setid(int id) { 
    this.id = id; 
  } 
 
  public string getname() { 
    return name; 
  } 
 
  public void setname(string name) { 
    this.name = name; 
  } 
 
  public date getbirthday() { 
    return birthday; 
  } 
 
  public void setbirthday(date birthday) { 
    this.birthday = birthday; 
  } 
 
  @override 
  public string tostring() { 
    return "student [birthday=" + birthday + ", id=" + id + ", name=" 
        + name + "]"; 
  } 
 
} 

public class teacher { 
  private int id; 
 
  private string name; 
 
  private string title; 
 
  public int getid() { 
    return id; 
  } 
 
  public void setid(int id) { 
    this.id = id; 
  } 
 
  public string getname() { 
    return name; 
  } 
 
  public void setname(string name) { 
    this.name = name; 
  } 
 
  public string gettitle() { 
    return title; 
  } 
 
  public void settitle(string title) { 
    this.title = title; 
  } 
 
  @override 
  public string tostring() { 
    return "teacher [id=" + id + ", name=" + name + ", title=" + title 
        + "]"; 
  } 
 
} 

注意这里定义了一个tabledata实体类:

import java.util.list; 
 
public class tabledata { 
 
  private string tablename; 
 
  private list tabledata; 
 
  public string gettablename() { 
    return tablename; 
  } 
 
  public void settablename(string tablename) { 
    this.tablename = tablename; 
  } 
 
  public list gettabledata() { 
    return tabledata; 
  } 
 
  public void settabledata(list tabledata) { 
    this.tabledata = tabledata; 
  } 
} 

测试类:
(仔细看将json转回为对象的实现,这里经过两次转化,第一次转回的结果是map不是我们所期望的对象,对map再次转为json后再转为对象,我引用的是gson2.1的jar处理正常,好像使用gson1.6的jar会报错,所以建议用最新版本)

import java.util.arraylist; 
import java.util.date; 
import java.util.list; 
 
import com.google.gson.gson; 
import com.google.gson.reflect.typetoken; 
 
public class gsontest5 { 
 
  /** 
   * @param args 
   */ 
  public static void main(string[] args) { 
    // 对象转为json-->start 
    student student1 = new student(); 
    student1.setid(1); 
    student1.setname("李坤"); 
    student1.setbirthday(new date()); 
 
    student student2 = new student(); 
    student2.setid(2); 
    student2.setname("曹贵生"); 
    student2.setbirthday(new date()); 
 
    student student3 = new student(); 
    student3.setid(3); 
    student3.setname("柳波"); 
    student3.setbirthday(new date()); 
 
    list<student> stulist = new arraylist<student>(); 
    stulist.add(student1); 
    stulist.add(student2); 
    stulist.add(student3); 
 
    teacher teacher1 = new teacher(); 
    teacher1.setid(1); 
    teacher1.setname("米老师"); 
    teacher1.settitle("教授"); 
 
    teacher teacher2 = new teacher(); 
    teacher2.setid(2); 
    teacher2.setname("丁老师"); 
    teacher2.settitle("讲师"); 
    list<teacher> teacherlist = new arraylist<teacher>(); 
    teacherlist.add(teacher1); 
    teacherlist.add(teacher2); 
 
    tabledata td1 = new tabledata(); 
    td1.settablename("students"); 
    td1.settabledata(stulist); 
 
    tabledata td2 = new tabledata(); 
    td2.settablename("teachers"); 
    td2.settabledata(teacherlist); 
 
    list<tabledata> tdlist = new arraylist<tabledata>(); 
    tdlist.add(td1); 
    tdlist.add(td2); 
    gson gson = new gson(); 
    string s = gson.tojson(tdlist); 
 
    system.out.println(s); 
    // 结果:[{"tablename":"students","tabledata":[{"id":1,"name":"李坤","birthday":"jun 22, 2012 10:44:16 am"},{"id":2,"name":"曹贵生","birthday":"jun 22, 2012 10:44:16 am"},{"id":3,"name":"柳波","birthday":"jun 22, 2012 10:44:16 am"}]},{"tablename":"teachers","tabledata":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}] 
    // 对象转为json-->end 
 
    // ///////////////////////////////////////////////////////////////////// 
 
    // 将json转为数据-->start 
    list<tabledata> tabledatas2 = gson.fromjson(s, 
        new typetoken<list<tabledata>>() { 
        }.gettype()); 
    for (int i = 0; i < tabledatas2.size(); i++) { 
      tabledata entitydata = tabledatas2.get(i); 
      string tablename = entitydata.gettablename(); 
      list tabledata = entitydata.gettabledata(); 
      string s2 = gson.tojson(tabledata); 
      // system.out.println(s2); 
      // system.out.println(entitydata.getdata()); 
      if (tablename.equals("students")) { 
        system.out.println("students"); 
        list<student> retstulist = gson.fromjson(s2, 
            new typetoken<list<student>>() { 
            }.gettype()); 
        for (int j = 0; j < retstulist.size(); j++) { 
          system.out.println(retstulist.get(j)); 
        } 
 
      } else if (tablename.equals("teachers")) { 
        system.out.println("teachers"); 
        list<teacher> rettchrlist = gson.fromjson(s2, 
            new typetoken<list<teacher>>() { 
            }.gettype()); 
        for (int j = 0; j < rettchrlist.size(); j++) { 
          system.out.println(rettchrlist.get(j)); 
        } 
      } 
    } 
 
    // json转为对象-->end 
  } 
} 

输出结果:

[{"tablename":"students","tabledata":[{"id":1,"name":"李坤","birthday":"jun 22, 2012 10:04:12 pm"},{"id":2,"name":"曹贵生","birthday":"jun 22, 2012 10:04:12 pm"},{"id":3,"name":"柳波","birthday":"jun 22, 2012 10:04:12 pm"}]},{"tablename":"teachers","tabledata":[{"id":1,"name":"米老师","title":"教授"},{"id":2,"name":"丁老师","title":"讲师"}]}] 
students 
student [birthday=fri jun 22 22:04:12 cst 2012, id=1, name=李坤] 
student [birthday=fri jun 22 22:04:12 cst 2012, id=2, name=曹贵生] 
student [birthday=fri jun 22 22:04:12 cst 2012, id=3, name=柳波] 
teachers 
teacher [id=1, name=米老师, title=教授] 
teacher [id=2, name=丁老师, title=讲师] 

注册typeadapter及处理enum类型

枚举类型给我们的程序带来了好处,如何用gson来实现与json的互转呢?请看本文.

本文重点掌握如何自己写一个typeadapter及注册typeadapter和处理enum类型.

实体类:

public enum packagestate { 
  play, update, updating, download, downloading, 
} 

public class packageitem { 
  private string name; 
  private packagestate state; 
  private string size; 
 
  public string getname() { 
    return name; 
  } 
 
  public void setname(string name) { 
    this.name = name; 
  } 
 
  public packagestate getstate() { 
    return state; 
  } 
 
  public void setstate(packagestate state) { 
    this.state = state; 
  } 
 
  public string getsize() { 
    return size; 
  } 
 
  public void setsize(string size) { 
    this.size = size; 
  } 
 
  @override 
  public string tostring() { 
    return "packageitem [name=" + name + ", size=" + size + ", state=" 
        + state + "]"; 
  } 
} 

自己写一个转换器实现jsonserializer<t>接口和jsondeserializer<t>接口:

import java.lang.reflect.type; 
 
import com.google.gson.jsondeserializationcontext; 
import com.google.gson.jsondeserializer; 
import com.google.gson.jsonelement; 
import com.google.gson.jsonparseexception; 
import com.google.gson.jsonprimitive; 
import com.google.gson.jsonserializationcontext; 
import com.google.gson.jsonserializer; 
 
public class enumserializer implements jsonserializer<packagestate>, 
    jsondeserializer<packagestate> { 
 
  // 对象转为json时调用,实现jsonserializer<packagestate>接口 
  @override 
  public jsonelement serialize(packagestate state, type arg1, 
      jsonserializationcontext arg2) { 
    return new jsonprimitive(state.ordinal()); 
  } 
 
  // json转为对象时调用,实现jsondeserializer<packagestate>接口 
  @override 
  public packagestate deserialize(jsonelement json, type typeoft, 
      jsondeserializationcontext context) throws jsonparseexception { 
    if (json.getasint() < packagestate.values().length) 
      return packagestate.values()[json.getasint()]; 
    return null; 
  } 
 
} 

测试类:

import com.google.gson.gson; 
import com.google.gson.gsonbuilder; 
 
public class gsontest6 { 
 
  public static void main(string[] args) { 
    gsonbuilder gsonbuilder = new gsonbuilder(); 
    gsonbuilder.registertypeadapter(packagestate.class, 
        new enumserializer()); 
    gson gson = gsonbuilder.create(); 
    packageitem item = new packageitem(); 
    item.setname("item_name"); 
    item.setsize("500m"); 
    item.setstate(packagestate.updating);// 这个 state是枚举值 
 
    string s = gson.tojson(item); 
    system.out.println(s); 
 
    system.out.println("--------------------------------"); 
 
    packageitem retitem = gson.fromjson(s, packageitem.class); 
    system.out.println(retitem); 
  } 
} 


输出结果(结果中已经将state的对应枚举类型转为了int类型):

{"name":"item_name","state":2,"size":"500m"} 
-------------------------------- 
packageitem [name=item_name, size=500m, state=updating]