gson TypeAdapter 和FieldNamingStrategy,SerializedName实现属性名称的设置别名

2024-10-09 10:46:42 浏览数 (1)

gson TypeAdapter 和FieldNamingStrategy,SerializedName实现属性名称的设置别名

代码语言:javascript复制
package com.example.core.mydemo.TypeAdapter;

import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.Field;

/**
 * 打印输出结果:
 jsonStr={"Result":null,"id":1,"data":null}
 bean=result:null id:1 data:null
 bean2=result:-1 id:1 data:null
 jsonStr2={"Result":-1,"id":1,"DATA":"Empty"}
 */
public class UserBean {
    @SerializedName("Result")
    public Integer result;
    public Long id;
    public String data;

    @Override
    public String toString() {
        return "result:" result " id:" id " data:" data;
    }

    public static void main(String[] args) {
//        Gson gson = new Gson();
        //serializeNulls输出null
        Gson gson = new GsonBuilder().serializeNulls().create();
        UserBean userBean = new UserBean();
        userBean.setId(1);
//        userBean.setData(null);
//        userBean.setResult(null);

        String jsonStr = gson.toJson(userBean);
        System.out.println("jsonStr="   jsonStr);
        UserBean bean = gson.fromJson(jsonStr,UserBean.class);
        System.out.println("bean="   bean.toString());


        Gson gson2 = new GsonBuilder()
                .registerTypeAdapter(String.class,new StringAdapter())
                .registerTypeAdapter(Integer.class,new IntegerAdapter())
                .registerTypeAdapter(int.class,new IntegerAdapter())
                .setFieldNamingStrategy(new FirstLowerCaseStrategy())
                .create();

        UserBean bean2 = gson2.fromJson(jsonStr,UserBean.class);
        System.out.println("bean2="   bean2.toString());

        System.out.println("jsonStr2="   gson2.toJson(bean2));


    }

    public int getResult() {
        return result;
    }

    public void setResult(Integer result) {
        this.result = result;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }


    public static class FirstLowerCaseStrategy implements FieldNamingStrategy {

        @Override
        public String translateName(Field f) {
//            System.out.println("name="   f.getName());
            if("data".equalsIgnoreCase(f.getName())){
//                return f.getName().toLowerCase();
//                System.out.println("upper="   f.getName().toUpperCase());
                return f.getName().toUpperCase();
            }else{
                return f.getName();
            }
        }
    }

}

0 人点赞