gson使用教程-翻譯7

原文地址:http://www.studytrails.com/java/json/java-google-json-custom-serializer-deserializer.jsp

就如我們之前看到的教程,Gson提供自定義序列化器和反序列化器.如果我們不需要Gson默認的轉換方式,我們可以通過自定義序列化器和反序列化器來轉換java對象和json.下面的第一個demo是展示自定義序列化器和第二個demo是展示自定義反序列化器.

Custom Serializer

自定義序列化器通過實現JsonSerializer這個接口和實現public JsonElement serialize(T src,Type typeOfSrc,JsonSerializationContext context)方法,src這個是轉換源對象,而Type是轉換源對象的類型.下面的demo展示如何創建和使用自定義序列化器.

 {
    @Override
    public JsonElement serialize(Dog src, Type typeOfSrc, JsonSerializationContext context) {
        // This method gets involved whenever the parser encounters the Dog
        // object (for which this serializer is registered)
        JsonObject object = new JsonObject();
        String name = src.getName().replaceAll(" ", "_");
        object.addProperty("name", name);
        // we create the json object for the dog and send it back to the
        // Gson serializer
        return object;
    }

    public static void main(String[] args) {
        Animall animal = new Animall();
        Dog dog = new Dog("I am a dog");
        animal.setAnimal(dog);
        // Create the GsonBuilder and register a serializer for the Dog class.
        // Whenever the Dog class is encountered Gson calls the DogSerializer
        // we set pretty printing own to format the json
        Gson gson = new GsonBuilder().registerTypeAdapter(Dog.class, new DogSerializer()).setPrettyPrinting().create();
        // Since Animal contains generic type create the type using TypeToken
        // class.
        Type animalType = new TypeToken>() {
        }.getType();
        System.out.println(gson.toJson(animal, animalType));
    }
}" data-snippet-id="ext.19d6ae7896b670d7d7016344b5a86c53" data-snippet-saved="false" data-csrftoken="H6orYN6d-60rAvmWUDDQffwRX5uiglInftYs" data-codota-status="done">package com.studytrails.json.gson;
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;

public class DogSerializer implements JsonSerializer<dog> {
    @Override
    public JsonElement serialize(Dog src, Type typeOfSrc, JsonSerializationContext context) {
        // This method gets involved whenever the parser encounters the Dog
        // object (for which this serializer is registered)
        JsonObject object = new JsonObject();
        String name = src.getName().replaceAll(" ", "_");
        object.addProperty("name", name);
        // we create the json object for the dog and send it back to the
        // Gson serializer
        return object;
    }

    public static void main(String[] args) {
        Animall<Dog> animal = new Animall<Dog>();
        Dog dog = new Dog("I am a dog");
        animal.setAnimal(dog);
        // Create the GsonBuilder and register a serializer for the Dog class.
        // Whenever the Dog class is encountered Gson calls the DogSerializer
        // we set pretty printing own to format the json
        Gson gson = new GsonBuilder().registerTypeAdapter(Dog.class, new DogSerializer()).setPrettyPrinting().create();
        // Since Animal contains generic type create the type using TypeToken
        // class.
        Type animalType = new TypeToken<Animal<Dog>>() {
        }.getType();
        System.out.println(gson.toJson(animal, animalType));
    }
}

Animal類

package com.studytrails.json.gson;

public class Animal<t> {

    public T animal;

    public void setAnimal(T animal) {
        this.animal = animal;
    }

    public T get() {
        return animal;
    }

}

Dog類

package com.studytrails.json.gson;

public class Dog {
    private String name;

    public Dog(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

}

Custom DeSerializer

使用一個自定義反序列化器把一個json轉換成Dog對象.通過實現JsonDeserializer接口來自定義反序列化器.

 {
    @Override
    public Dog deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String name = json.getAsJsonObject().get("name").getAsString();
        name = name.replace(" ", "_");
        Dog dog = new Dog(name);

        return dog;
    }

    public static void main(String[] args) {
        String json = "{\"animal\":{\"name\":\"I am a dog\"}}";
        Gson gson = new GsonBuilder().registerTypeAdapter(Dog.class, new DogDeserialiser()).create();
        Type animalType = new TypeToken>() {
        }.getType();
        Animal animal = gson.fromJson(json, animalType);
        System.out.println(animal.get().getName());
    }

}" data-snippet-id="ext.3017f7a7ba1ebf41f635c2ec3d29f14c" data-snippet-saved="false" data-csrftoken="z96XQvXq-Fck8AgZ_ntRhJ8TzJ8SNi348GPA" data-codota-status="done">  package com.studytrails.json.gson;

import java.lang.reflect.Type;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;

public class DogDeserialiser implements JsonDeserializer<Dog> {
    @Override
    public Dog deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        String name = json.getAsJsonObject().get("name").getAsString();
        name = name.replace(" ", "_");
        Dog dog = new Dog(name);

        return dog;
    }

    public static void main(String[] args) {
        String json = "{\"animal\":{\"name\":\"I am a dog\"}}";
        Gson gson = new GsonBuilder().registerTypeAdapter(Dog.class, new DogDeserialiser()).create();
        Type animalType = new TypeToken<Animal<Dog>>() {
        }.getType();
        Animal<Dog> animal = gson.fromJson(json, animalType);
        System.out.println(animal.get().getName());
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章