Json转换利器-Gson

Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来

实体类:

public class ClassRoom {
    @Expose
    @SerializedName("楼层")
    private String floor;
    @Expose
    private String name;
    @Expose
    private Date date;
    ...get set ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
public class Student {
    @Expose
    private int id;
    @Expose
    private String name;
    @Expose
    private int age;
    ...get set ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
public class Teacher {
    @Expose(deserialize=false)
    private int id;
    @Expose
    private String name;
    @Expose
    private int age;
    @Expose
    private List<Student> students;
    @Expose
    private ClassRoom room;
    ...get set ...
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

测试:

import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

import org.demo.model.ClassRoom;
import org.demo.model.Student;
import org.demo.model.Teacher;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


public class test {
    public static void main(String[] args) {
        String json = getBean();
        System.out.println(json);

        Gson gson = new GsonBuilder()
            .excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();

        System.out.println("--------------转为javaBean--------------");
        Teacher teacher = gson.fromJson(json, Teacher.class);
        System.out.println(teacher.toString());

        ClassRoom room = teacher.getRoom();
        System.out.println(room);
    }

    public static String getBean(){
        System.out.println("--------------转为Json字符串--------------");
        ClassRoom room = new ClassRoom();
        room.setName("三年二班");
        room.setFloor("5楼");
        room.setDate(new Date(System.currentTimeMillis()));

        Student student1 = new Student();
        student1.setId(1);
        student1.setName("小飞");
        student1.setAge(11);

        Student student2 = new Student();
        student2.setId(2);
        student2.setName("小天");
        student2.setAge(11);

        Student student3 = new Student();
        student3.setId(3);
        student3.setName("小恩");
        student3.setAge(11);

        List<Student> list = new ArrayList<Student>();
        list.add(student1);
        list.add(student2);
        list.add(student3);

        Teacher teacher = new Teacher();
        teacher.setId(1);
        teacher.setName("苍老师");
        teacher.setAge(32);
        teacher.setStudents(list);
        teacher.setRoom(room);

        Gson gson = new GsonBuilder()
            .setPrettyPrinting()                    //对json结果格式化.
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();

        //也可以用new Gson() 但有些东西可能会不符合要求
//      Gson gson = new Gson();

        return gson.toJson(teacher);

    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79

结果:

--------------转为Json字符串--------------
{
  "id": 1,
  "name": "苍老师",
  "age": 32,
  "students": [
    {
      "id": 1,
      "name": "小飞",
      "age": 11
    },
    {
      "id": 2,
      "name": "小天",
      "age": 11
    },
    {
      "id": 3,
      "name": "小恩",
      "age": 11
    }
  ],
  "room": {
    "楼层": "5楼",
    "name": "三年二班",
    "date": "2016-03-24 10:49:21"
  }
}
--------------转为javaBean--------------
Teacher [id=0, name=苍老师, age=32, students=[Student [id=1, name=小飞, age=11, teacher=null], Student [id=2, name=小天, age=11, teacher=null], Student [id=3, name=小恩, age=11, teacher=null]], room=ClassRoom [floor=5楼, name=三年二班, date=2016-03-24]]
ClassRoom [floor=5楼, name=三年二班, date=2016-03-24]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

这里需要注意GsonBuilder含有的方法:

  • excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性
  • enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
  • serializeNulls().setDateFormat(“yyyy-MM-dd HH:mm:ss:SSS”) //时间转化为特定格式
  • setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) //会把字段首字母大写,对于实体上使用了@SerializedName注解的不会生效.
  • setPrettyPrinting() //对json结果格式化.
  • setVersion(1.0) //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化. 
    //@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么 
    //@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.

Gson的注解 
@Expose 属性将不会被序列化和反序列化 
@Expose(serialize=false) 属性将不会被序列化 
@Expose(deserialize=false) 属性将不会被反序列化 
@SerializedName(“xxx”) 属性序列化后的名字 


发布了74 篇原创文章 · 获赞 58 · 访问量 24万+

猜你喜欢

转载自blog.csdn.net/Jason_996/article/details/78030624