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());
    }

}
    
    
   
   
  
  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值