Gson笔记

转自:http://blog.sina.com.cn/s/blog_807f4f4e0100yw0f.html

官网是最好的学习通道
https://www.zxproxy.com/browse.php?u=PoVWZG8IRnWFg4MYzPJJAtBHtKbXBm3UMAF9kXdqMJS7W9Gap+o0TUstD6+1&b=6&f=norefer

UserGuide 解释了Gson 解析 大部分应用

Gson  用来 JavaBean --> json 格式  ||     json 格式  -- > JavaBean

前者称  Gson 的 序列化  后者 Gson 的反序列化

Primitives Examples   //基本例子

ps Serialization :JavaBean --> json 格式

    Deserialization: json 格式  -- > JavaBean

(Serialization)
Gson gson = new Gson();

gson.toJson(1);            ==> prints 1
gson.toJson("abcd");       ==> prints "abcd"
gson.toJson(new Long(10)); ==> prints 10
int[] values = { 1 };
gson.toJson(values);       ==> prints [1]

(Deserialization)
int one =
 gson.fromJson("1", int.class);
Integer one = gson.fromJson("1", Integer.class);
Long one = gson.fromJson("1", Long.class);
Boolean false =
 gson.fromJson("false", Boolean.class);
String str =
 gson.fromJson(""abc"", String.class);
String anotherStr = gson.fromJson("["abc"]", String.class);


Object Examples //自定义类

class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}

(Serialization)
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj); 
==> json is {"value1":1,"value2":"abc"}   //注意 这里没有出现 value3  = 3  
java 关键字transient
 

如果用transient声明一个实例变量,当对象存储时,它的值不需要维持
Gson 也就不会序列化他


(Deserialization)

BagOfPrimitives obj2 =
 gson.fromJson(json, BagOfPrimitives.class);  

Finer Points with Objects //小小细节

1. 序列化一个空字段将跳过
   反序列化设置对象中的相应字段条目丢失JSON结果为null

如果一个字段人工合成的,会被忽略不包括JSON序列化或反序列化
相应的内部类匿名类局部类领域被忽略,并且不包括在序列化或反序列化


Nested Classes (including Inner Classes) //嵌套类(包含内部类)

ublic class A {
  public String a;

  class B {

    public String b;

    public B() {
      // No args constructor for B
    }
  }
}


//这是一个成员内部类 Gson 序列化A时  不会序列化 B
A a =new A();
a.a="aaaaaa";

A.B b =new a.new B();
b.b="bbbbbb";
Gson g =new Gson();
String atext = g.toJson(a);
System.out.println(atext);

json-->"a":"aaaaaa"

Array Examples  //数组例子

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

(Serialization)
gson.toJson(ints);     ==> prints [1,2,3,4,5]
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

(Deserialization)
int[] ints2 =
 gson.fromJson("[1,2,3,4,5]", int[].class);
==> ints2 will be same as ints


支持多维数组任意复杂元素类型

Collections Examples    //集合<泛形>实例

Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

(Serialization)
String json =
 gson.toJson(ints); ==> json is [1,2,3,4,5]

(Deserialization)

//使用反序列化   如果要保持泛形 
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 =
 gson.fromJson(json, collectionType);
ints2 is same as ints

Fairly hideous: note how we define the type of collection
Unfortunately, no way to get around this in Java


Serializing and Deserializing Generic Types   泛型类型

Type fooType = new TypeToken<Foo<Bar>>() {}.getType();
gson.toJson(foo, fooType);

gson.fromJson(json, fooType)

Serializing and Deserializing Collection with Objects of Arbitrary Types 任意对像类型的集合

['hello',5,{name:'GREETINGS',source:'guest'}]

The equivalent Collection containing this is:
Collection collection = new ArrayList();
collection.add("hello");
collection.add(5);
collection.add(new Event("GREETINGS", "guest"));
Where the Event class is defined as:
class Event {
  private String name;
  private String source;
  private Event(String name, String source) {
    this.name = name;
    this.source = source;
  }
}
 

{name:'GREETINGS',source:'guest'} 不会被解析称Event 类

Excluding Fields From Serialization and Deserialization 过滤字段

Gson's @Expose   使用Annotaion 注解方式

@Expose
private String name; 

private int age;
Gson g =new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String pStr = g.toJson(p);  p 为person 的实例

只会输出name  不会输出名字

{"name":"hsahga"}

反序列化同理

User Defined Exclusion Strategies  用户自定义排出策略  解决硬编码



public class MyExclusionStrategy implements ExclusionStrategy {

    private  Class<?>[] clazzs; // 要过滤得类数组
   
    private  String[]  fileds;  //要过滤的属性数组 
   
   

    public MyExclusionStrategy(Class<?>[] clazzs,String[] fileds) {
       
        this.clazzs = clazzs;
        this.fileds= fileds;

       
    }
   
   
    public MyExclusionStrategy(Class<?>[] clazzs)
    {
       
        this.clazzs = clazzs ;
    }
   
   
    public MyExclusionStrategy(String[] fileds)
    {
       
        this.fileds = fileds ;
    }
   

   

    @Override
    public boolean shouldSkipClass(Class<?> clazz02) {

        if (this.clazzs == null) {
            return false;
        }

        for (int i = 0; i < this.clazzs.length; i++) {

            if (clazz02.getName().equals(clazzs[i].getName())) {
                return true;
            }
        }

        return false;
    }

   

    @Override
    public boolean shouldSkipField(FieldAttributes f) {
       
        if(f == null)
        {
            return false ;
        }
       
       
       
       
        for(String field : this.fileds)
        {
            String[] str = field.split("_");
           
            if(f.getDeclaringClass().toString().equals(str[1]))
            {
               
            if(str[0].equals(f.getName()))
            {
                return true ;
            }
           
        }
       
        }
        return false;
       
       
        //要使用注解 排除属性  请解封下面这段话  并且屏蔽掉上面的
        //return f.getAnnotation(NoSeriaizle.class) != null;    通过注解 (@NoSeriaizle)
    }

}

或者通过注解 (@NoSeriaizle)

package Inner;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface NoSeriaizle {

}
在要使用的属性上:

@NoSeriaizle
    private String name;   排除 name

原文地址:https://www.cnblogs.com/ct732003684/p/3078702.html