Gson系列4 --- 策略篇 -- FieldNamingStrategy

本文介绍了如何使用Gson的FieldNamingStrategy策略来修改实体类属性的命名规则,包括将属性名全部转换为大写以及在属性名前后添加特定前缀或后缀。通过注解和实体类的实例,展示了具体实现过程。

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

1、简述

[FieldNamingStrategy]  
属性命名策略 --
   用于自定义 json  key 的形式 
   new GsonBuilder()
     // 采用自定义的策略
    .setFieldNamingStrategy(new FieldStrategy.AllUpperCaseStrategy())
    // 采用 默认类的策略
    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DOTS)
    .create();
   -- 注意: 只能有一个策略起作用。
   

2、实体类

实现以下功能 ① 让属性的名称 全部改为大写,

如 username ---->  USERNAME

  userId ---->  USERID

或者 实现 在属性名的前后面 加上前缀 或后缀

注解类如下

package sun.rain.amazing.gson.strategy.field;

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

/**
 * 采用注解的用于改变 对应的key * @author Reese
 */
@Target( ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GsonKeyValue {
    String value() default "";
    String prefix() default "";
    String suffix() default "";

}
给属性添加前缀 或后缀

@GsonKeyValue(prefix = "CN_", suffix = "_AN")

private String mobile;

变成  mobile  --->   CN_mobile_AN:  "xxx"

package sun.rain.amazing.gson.strategy.field;

import com.google.gson.FieldNamingStrategy;

import java.lang.reflect.Field;

/**
 * 命名策略
 * @author sunRainAmazing
 */
public class FieldStrategy {

    /**
     * 采用全部大写的形式
  */
    public static class AllUpperCaseStrategy implements FieldNamingStrategy{
        @Override
        public String translateName(Field f) {
            return f.getName().toUpperCase();
        }
    }

    /**
     * 添加前置 和 后置 注解
  */
    public static class GsonKeyValueCaseStrategy implements FieldNamingStrategy{
        @Override
        public String translateName(Field f) {
            GsonKeyValue gkv = f.getAnnotation(GsonKeyValue.class);
            if(gkv != null){
                if(gkv.value().length()>0){
                    return gkv.prefix() + gkv.value() + gkv.suffix();
                }else{
                    return gkv.prefix() + f.getName() + gkv.suffix();
                }
            }else{
                return f.getName();
            }

        }
    }
}

实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class GsonField {
    private Integer id;
    @SerializedName("user_name")
    private String name;
    private String email;
}

package sun.rain.amazing.gson.strategy.field;

import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author sunRainAmazing
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GsonFieldKey {
    private Integer id;
    @SerializedName("user_name")
    private String name;
    @GsonKeyValue(prefix = "QQ_")
    private String email;
    @GsonKeyValue(prefix = "CN_", suffix = "_AN")
    private String mobile;
    @GsonKeyValue(value="desc_info", prefix = "CN_", suffix = "_AN")
    private String extra;
}


3、测试类

package sun.rain.amazing.gson.strategy;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import sun.rain.amazing.gson.strategy.field.FieldStrategy;
import sun.rain.amazing.gson.strategy.field.GsonField;
import sun.rain.amazing.gson.strategy.field.GsonFieldKey;

/**
 * @author sunRainAmazing
 */
public class GsonFieldTest {

    Gson gson = new Gson();


    /**
     * 默认注解 优先级 高于自定义的 属性名策略
  *     {"ID":10,  "user_name":"tom",  "EMAIL":"a@a.com"}
     *   GsonField(id=10, name=tom, email=a@a.com)
     */
    @Test
    public void test(){
        GsonField g = new GsonField(10,"tom","a@a.com");

        gson = new GsonBuilder()
                .setFieldNamingStrategy(new FieldStrategy.AllUpperCaseStrategy())
                .create();
        String json = gson.toJson(g);
        System.out.println(json);

        g = gson.fromJson(json,GsonField.class);
        System.out.println(g);
    }

    /**
     * 只能有一个命名策略起作用
     * {"id":10,"user_name":"tom","QQ_email":"a@a.com",
     *              "CN_mobile_AN":"12025",
     *              "CN_desc_info_AN":"this is some message"}
     *
     * GsonFieldKey(id=10, name=tom, email=a@a.com, mobile=12025,
     *              extra=this is some message)
     */
    @Test
    public void test1(){
        GsonFieldKey g = new GsonFieldKey(10,"tom","a@a.com"
        ,"12025","this is some message");

        gson = new GsonBuilder()
                .setFieldNamingStrategy(new FieldStrategy.AllUpperCaseStrategy())
                .setFieldNamingStrategy(new FieldStrategy.GsonKeyValueCaseStrategy())
                .create();
        String json = gson.toJson(g);
        System.out.println(json);

        g = gson.fromJson(json,GsonFieldKey.class);
        System.out.println(g);
    }




}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值