gson使用教程-翻訳8

8510 ワード

原文の住所:http://www.studytrails.com/java/json/java-google-json-exclusion-strategy.jsp
このセクションでは、Javaオブジェクトの中のいくつかの属性をJson.Gsonに変換するにはどうやって選択するかを見ます.デフォルトでは、javaオブジェクトの中のすべての属性をJsonに変換します.しかし、時にはそれらの属性をコントロールしたいです.これらの属性は変えられません.このような制御方法はいくつかあります.ソースがないタイプでも大丈夫です.異なる方法:-カスタム注釈を使って注釈を無視する属性-Exclusion Strategyインターフェースを実現することとshuldSkipFiledとshuldSkipClass方法を実現することによって、@Expose注解とGsonBuider excledouderを使用します.@Exposeコメントを使用していない属性は無視されます.以下のdemoはこの3つの方法を示します.
package com.studytrails.json.gson;
import java.awt.Color;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class ExclusionExample {
    public static void main(String[] args) {
        // We create an instance of type CAT.
        Cat cat = new Cat();
        cat.setName("Cat");
        cat.setAge(1);
        cat.setColor(Color.BLACK);
        cat.setCountry("US");
        // we allow serializing null. therefore although the fields lazy is
        // null, it will be serialized. We add a CustomExclusionStrategy that
        // will exclude the Color class. We also allow only those fields that
        // have been exposed using the @Expore annotation
        Gson gson = new GsonBuilder().serializeNulls().setExclusionStrategies(new CustomExclusionStrategy(Color.class))
                .excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gson.toJson(cat));
        // prints {"name":"Cat","lazy":null}

    }
}
Cat類
package com.studytrails.json.gson;
import java.awt.Color;
import com.google.gson.annotations.Expose;
public class Cat {
    @Expose
    private String name;
    private int age;
    private Color color;
    @Expose
    @Country
    private String country;
    @Expose
    private Boolean lazy = null;

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

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

    public void setColor(Color color) {
        this.color = color;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public Color getColor() {
        return color;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCountry() {
        return country;
    }

    public void setLazy(Boolean lazy) {
        this.lazy = lazy;
    }

    public Boolean getLazy() {
        return lazy;
    }
}
Exclusion Strategy
package com.studytrails.json.gson;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
/** * This class defines custom exclusion policy. We want to ignore all fields that * have been annotated with the Country annotation. Note that we can also ignore * fields based on name or type. This same policy can be applied to any class. * In this example we apply to the CAT class, but it is not limited to the cat * class. * */
public class CustomExclusionStrategy implements ExclusionStrategy {
    private Class classToExclude;
    public CustomExclusionStrategy(Class classToExclude) {
        this.classToExclude = classToExclude;
    }
    // This method is called for all fields. if the method returns false the
    // field is excluded from serialization
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        if (f.getAnnotation(Country.class) == null)
            return false;
        return true;
    }
    // This method is called for all classes. If the method returns false the
    // class is excluded.
    @Override
    public boolean shouldSkipClass(Class<?> clazz) {
        if (clazz.equals(classToExclude))
            return true;
        return false;
    }
}