Gson系列3 --- 注解篇 -- @JsonAdapter

本文详细探讨了Gson库中的@JsonAdapter注解,介绍其作用及用法,通过实例分析展示了如何在序列化和反序列化过程中自定义适配器,提升数据转换效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、简述

[@JsonAdapter -- GsonBuilder/Gson] 
  针对于非null值, 若存在null 值 , 则不会起作用     
  主要用于序列化,可放置在属性上,
    该对应的value值 必须 实现 JsonSerializer<T>接口
        对于属性 为 null值 , new Gson() 则不进行序列化  
    反序列化 则 需要实现 JsonDeserializer<T> 接口

2、基本类

package sun.rain.amazing.gson.anno;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import sun.rain.amazing.gson.anno.adapter.*;

import java.util.Date;

/**
 * JsonAdapter
 *   用来自定义序列化 和 反序列化
 *
 * 这种形式比较单一 ,  
 *   序列化 : 放置在 该类的属性上
 *    反序列化时: 实现 JsonDeserializer<该类名>
 *     
 *
 *   开可以不采用注解的形式 进行 手动设置
 *      Gson gson = new GsonBuilder()
 *                      .setDateFormat("yyyy-MM-dd HH:mm:ss")
 *                      .create(); //按照 yyyy-MM-dd HH:mm:ss格式化。
 *                      
 * @JsonAdapter(JsonAdapterGsonDeserializer.class)
 *    对类的进行反序列化
*
 * @author sunRainAmazing
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonAdapter(JsonAdapterGsonDeserializer.class)
public class JsonAdapterGson {

    private String name;
    private String email;
    private String mobile;

    @JsonAdapter(DateFormatSerializer.class)
    private Date birthday;
    @JsonAdapter(DateTimeFormatSerializer.class)
    private Date regTime;

    private Date upTime;

    public JsonAdapterGson(String name, String email, 
                           String mobile, Date birthday, Date regTime) {
        this.name = name;
        this.email = email;
        this.mobile = mobile;
        this.birthday = birthday;
        this.regTime = regTime;
    }
}
package sun.rain.amazing.gson.anno.adapter;

import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sunRainAmazing
 */
public class DateFormatSerializer implements JsonSerializer<Date> {
    /**
     *
     * @param src 所需要序列化的值
     * @param typeOfSrc 序列化的类型
     * @param context 序列化的操作
     * @return
     */
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(new SimpleDateFormat("yyyy-MM-dd").format(src));
    }
}
package sun.rain.amazing.gson.anno.adapter;

import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sunRainAmazing
 */
public class DateTimeFormatSerializer implements JsonSerializer<Date> {
    /**
     *
     * @param src 所需要序列化的值
   * @param typeOfSrc 序列化的类型
   * @param context 序列化的操作
   * @return
     */
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return context.serialize(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(src));
    }
}
package sun.rain.amazing.gson.anno.adapter;

import com.google.gson.*;
import sun.rain.amazing.gson.anno.JsonAdapterGson;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author sunRainAmazing
 */
public class JsonAdapterGsonDeserializer implements JsonDeserializer<JsonAdapterGson> {
    /**
     * 只能实现类的 反序列化
  * 对于属性的反序列化 不能使用该注解
  * 且功能单一
  * @param json
     * @param typeOfT
     * @param context
     * @return
     * @throws JsonParseException
     */
    @Override
    public JsonAdapterGson deserialize(JsonElement json, Type typeOfT, 
                                       JsonDeserializationContext context) 
            throws JsonParseException {
        System.out.println(typeOfT);
        JsonObject jsonObj = json.getAsJsonObject();
        String name = jsonObj.get("name").getAsString();
        String email = jsonObj.get("email").getAsString();
        String mobile = jsonObj.get("mobile").getAsString();
        Date bir = null;
        Date reg = null;
        try {
            bir = new SimpleDateFormat("yyyy-MM-dd").
                    parse(jsonObj.get("birthday").getAsString());
            reg = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").
                    parse(jsonObj.get("regTime").getAsString());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new JsonAdapterGson(name,email,mobile,bir,reg);
    }
}

3、测试类

package sun.rain.amazing.gson.anno;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;

import java.util.Date;

/**
 * @author Reese
 */
public class JsonAdapterGsonTest {

    private Gson gson = new Gson();

    /**
     * {"name":"a","email":"b@b.com","mobile":"12305",
     *              "birthday":"2018-07-05",
     *              "regTime":"2018-07-05 15:14:00",
     *              "upTime":"Jul 5, 2018 3:14:00 PM"}
     *
     * JsonAdapterGson(name=a, email=b@b.com, mobile=12305,
     *              birthday=Thu Jul 05 00:00:00 CST 2018,
     *              regTime=Thu Jul 05 15:14:00 CST 2018, upTime=null)
     *
     * {"name":"a","email":"b@b.com","mobile":"12305",
     *              "birthday":"2018-07-05","regTime":"2018-07-05 15:14:00",
     *              "upTime":"Jul 5, 2018 3:14:00 PM"}
     *
     * {"name":"a","email":"b@b.com","mobile":"12305",
     *              "birthday":"2018-07-05","regTime":"2018-07-05 15:14:00",
     *              "upTime":"2018-07"}
     */
    @Test
    public void testJsonAdapterGsonSerializer(){
        JsonAdapterGson g = new JsonAdapterGson("a","b@b.com","12305",
                new Date(),new Date(),new Date());
        String json = gson.toJson(g);
        System.out.println(json);
        // json 反序列化
    JsonAdapterGson u = gson.fromJson(json,JsonAdapterGson.class);
        System.out.println(u);

        gson = new GsonBuilder().create();
        json = gson.toJson(g);
        System.out.println(json);

        //注解的形式 高于 优先级要高于GsonBuilder中指定的格式。
    gson = new GsonBuilder().setDateFormat("yyyy-MM").create();
        json = gson.toJson(g);
        System.out.println(json);
    }


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值