Gson源码解析之-toJson

Gson 是开发中我们经常使用的一款json 解析框架,也是Google 推出的诸多良品之一,今天我们就从源码的角度看下gson 是如何来做序列化的,即如何通过toJson方法来做序列化的。

 首先是获取Gson对象,只是Gson提供的对外方法类,有两种方式获取Gson对象,大概了解下。


        GsonBuilder gsonBuilder=new GsonBuilder();
        Gson BuGson=gsonBuilder.create();
        Gson gson = new Gson();

序列化大概的步骤:

   1.将类对象获取适配器对象

   2.通过反射机制获取对象的方法名字段和值

   3.通过流将每个字段对应的键和值逐个写入拼接

   4.输出序列化后的json 字符串

因为Gson本身有多种适配器类型,就找了一个比较有代表性的类型适配器

ReflectiveTypeAdapterFactory 类

为了更好理解,先来个实体类,他对应的ReflectiveTypeAdapterFactory 适配器,字段中的注解暂时忽略

public class TestMode {
    @Expose(deserialize = true)
    private int age;

    @Expose(serialize = false, deserialize = true)
    String name;
    @Expose(deserialize = true)
    @SerializedName("len")
    int length;
    public TestMode(){
    }

    public TestMode(int age, String name, int length) {
        this.age = age;
        this.name = name;
        this.length = length;
    }

    public int getLength() {
        return length;
    }

    public void setLength(int length) {
        this.length = length;
    }



    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "TestMode{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", length=" + length +
                '}';
    }
}

两种初始化Gson都可以,今天就不说他俩的区别了,后边会再出一篇具体讲GsonBuilder 使用,直接看Gson 构造函数

public Gson() {
    this(Excluder.DEFAULT, FieldNamingPolicy.IDENTITY,
        Collections.<Type, InstanceCreator<?>>emptyMap(), DEFAULT_SERIALIZE_NULLS,
        DEFAULT_COMPLEX_MAP_KEYS, DEFAULT_JSON_NON_EXECUTABLE, DEFAULT_ESCAPE_HTML,
        DEFAULT_PRETTY_PRINT, DEFAULT_LENIENT, DEFAULT_SPECIALIZE_FLOAT_VALUES,
        LongSerializationPolicy.DEFAULT, null, DateFormat.DEFAULT, DateFormat.DEFAULT,
        Collections.<TypeAdapterFactory>emptyList(), Collections.<TypeAdapterFactory>emptyList(),
        Collections.<TypeAdapterFactory>emptyList());
  }

  Gson(Excluder excluder, FieldNamingStrategy fieldNamingStrategy,
      Map<Type, InstanceCreator<?>> instanceCreators, boolean serializeNulls,
      boolean complexMapKeySerialization, boolean generateNonExecutableGson, boolean htmlSafe,
      boolean prettyPrinting, boolean lenient, boolean serializeSpecialFloatingPointValues,
      LongSerializationPolicy longSerializationPolicy, String datePattern, int dateStyle,
      int timeStyle, List<TypeAdapterFactory> builderFactories,
      List<TypeAdapterFactory> builderHierarchyFactories,
      List<TypeAdapterFactory> factoriesToBeAdded) {
    this.excluder = excluder;
    this.fieldNamingStrategy = fieldNamingStrategy;
    this.instanceCreators = instanceCreators;
    this.constructorConstructor = new ConstructorConstructor(instanceCreators);
    this.serializeNulls = serializeNulls;
    this.complexMapKeySerialization = complexMapKeySerialization;
    this.generateNonExecutableJson = generateNonExecutableGson;
    this.htmlSafe = htmlSafe;
    this.prettyPrinting = prettyPrinting;
    this.lenient = lenient;
    this.serializeSpecialFloatingPointValues = serializeSpecialFloatingPointValues;
    this.longSerializationPolicy = longSerializationPolicy;
    this.datePattern = datePattern;
    this.dateStyle = dateStyle;
    this.timeStyle = timeStyle;
    this.builderFactories = builderFactories;
    this.builderHierarchyFactories = builderHierarchyFactories;

    List<TypeAdapterFactory> factories = new ArrayList<TypeAdapterFactory>();

    // built-in type adapters that cannot be overridden
    factories.add(TypeAdapters.JSON_ELEMENT_FACTORY);
    factories.add(ObjectTypeAdapter.FACTORY);
Gson是Google的一个开源项目,可以将Java对象转换成JSON,也可能将JSON转换成Java对象。 Gson里最重要的对象有2个GsonGsonBuilder Gson有2个最基本的方法 1) toJson() – 转换java 对象到JSON 2) fromJson() – 转换JSON到java对象 下面是几个小例子 1. toJson() example Java 代码 收藏代码 1. class TestObjectToJson { 2. private int data1 = 100; 3. private String data2 = "hello"; 4. } 5. 6. TestObjectToJson obj = new TestObjectToJson(); 7. Gson gson = new Gson(); 8. String json = gson.toJson(obj); class TestObjectToJson { private int data1 = 100; private String data2 = "hello"; } TestObjectToJson obj = new TestObjectToJson(); Gson gson = new Gson(); String json = gson.toJson(obj); 会输出 {"data1":100,"data2":"hello"} 2. fromJson() example Java 代码 收藏代码 1. import com.google.gson.Gson; 2. 3. class TestJsonFromObject { 4. private int data1; 5. private String data2; 6. } 7. 8. String json = "{'data1':100,'data2':'hello'}"; 9. Gson gson = new Gson(); 10. TestJsonFromObject obj = gson.fromJson(json, TestJsonFromObject.class); import com.google.gson.Gson; class TestJsonFromObject { private int data1; private String data2; } String json = "{'data1':100,'data2':'hello'}"; Gson gson = new Gson(); TestJsonFromObject obj = gson.fromJson(json, TestJsonFromObject.class); 3. 将Java对象的属性转换成指定的JSON名字 Java 代码 收藏代码 1. import com.google.gson.FieldNamingPolicy; 2. import com.google.gson.Gson; 3. import com.google.gson.GsonBuilder; 4. import com.google.gson.annotations.SerializedName; 5. 6. public class TestGson { 7. 8. @SerializedName("first_field") 9. private String field1; 10. 11. private String secondField; 12. 13. public TestGson(String param1, String param2) { 14. field1 = param1; 15. secondField = param2; 16. } 17. } 18. 19. TestGson obj = new TestGson("aaaa", "bbbbb"); 20. Gson gson = new Gson
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值