1. 程式人生 > >gson序列化物件(值為空也序列化、值為null轉換為""、排除策略)

gson序列化物件(值為空也序列化、值為null轉換為""、排除策略)

修改記錄

日期 提出 說明
2018-03-23 20:08 @bxl049 AnnotationExclusion、FieldExclusion這兩哥類程式碼也沒有貼呀
2018-01-03 17:24 @xianglin007 你這個只能將String型別的null轉為空字串啊,如果是Int、Long、ArrayList呢?那豈不是要寫全部的資料型別,如果不管是什麼型別都轉換為空字串,這個就不行了,比如Int型別的null只能轉為Int不能轉為空字串。

gson序列化物件

/**
*YC 
*2017年8月1日 下午4:59:14
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.utils.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.huiw.core.uic.common.adapter.NullStringToEmptyAdapterFactory; import com.huiw.core.uic.common.utils.converter.AnnotationExclusion; import com.huiw.core.uic.common.utils.converter.FieldExclusion; /** * @author
YC 獲取一個完美gson: * */
public class PerfectGson { /** * * YC 2017年8月1日 下午5:09:34 * <p> * Title: getGson * </p> * <p> * Description: * <h1>完美gson具有如下功能:</h1> * <p> * 1、serializeNulls(值為空也序列化) * </p> * <p> * 2、registerTypeAdapterFactory(new * NullStringToEmptyAdapterFactory())(值為null轉換為"") * </p> * <p> * 3、.setExclusionStrategies(new TargetStrategy())(排除策略 ) * </p> * * @return
*/
public static Gson getGson() { return new GsonBuilder().serializeNulls() .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>()) .setExclusionStrategies(new AnnotationExclusion()).create(); } /** * * YC 2017年8月11日 下午2:39:33 * <p> * Title: getGson * </p> * <p> * Description: 帶參 * </p> * * @param strs * @return */ public static Gson getGson(String[] strs) { return new GsonBuilder().serializeNulls() .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>()) .setExclusionStrategies(new FieldExclusion(strs)).create(); } }

AnnotationExclusion類

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.huiw.archives.common.annotation.MyExclus;

/**
 * YC 2017年8月1日 下午2:39:22
 * <p>
 * Title:排除策略
 * </p>
 * <p>
 * Description: 用於排除一個類不用轉換的欄位
 * </p>
 */
public class AnnotationExclusion implements ExclusionStrategy {

    /**
     * 
     * YC 2017年8月1日 下午2:41:39
     * <p>
     * Title: shouldSkipClass
     * </p>
     * <p>
     * Description: 應該排除的類
     * </p>
     * 
     * @param class1
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class)
     */
    @Override
    public boolean shouldSkipClass(Class<?> class1) {
        return false;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:57
     * <p>
     * Title: shouldSkipField
     * </p>
     * <p>
     * Description: 應該排除的欄位
     * </p>
     * 
     * @param fieldattributes
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.FieldAttributes)
     */
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
         //如果屬性帶有MyExclus 註解,則排除
        return f.getAnnotation(MyExclus.class) != null;
    }

}

FieldExclusion類

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.huiw.archives.common.annotation.MyExclus;

/**
 * YC 2017年8月1日 下午2:39:22
 * <p>
 * Title:手動欄位排除策略
 * </p>
 * <p>
 * Description: 用於排除一個類不用轉換的欄位
 * </p>
 */
public class FieldExclusion implements ExclusionStrategy {
    String[] inStr;

    public FieldExclusion(String[] outStr) {
        this.inStr = outStr;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:39
     * <p>
     * Title: shouldSkipClass
     * </p>
     * <p>
     * Description: 應該排除的類
     * </p>
     * 
     * @param class1
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipClass(java.lang.Class)
     */
    @Override
    public boolean shouldSkipClass(Class<?> class1) {
        return false;
    }

    /**
     * 
     * YC 2017年8月1日 下午2:41:57
     * <p>
     * Title: shouldSkipField
     * </p>
     * <p>
     * Description: 應該排除的欄位
     * </p>
     * 
     * @param fieldattributes
     * @return
     * @see com.google.gson.ExclusionStrategy#shouldSkipField(com.google.gson.FieldAttributes)
     */
    @Override
    public boolean shouldSkipField(FieldAttributes f) {
        boolean flag = false;

        for (int i = 0; i < inStr.length; i++) {
            // 手動排除inStr串指定欄位
            if (f.getName().equals(inStr[i])) {
                flag = true;
                System.out.println("排除欄位===============>" + f.getName());
            } else {
                // 如果屬性帶有MyExclus 註解,則排除
                flag = f.getAnnotation(MyExclus.class) != null;
            }
        }

        return flag;
    }

}

MyExclus介面

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

/**
 * @author YC 如果屬性帶有MyExclus 註解,則GSON轉換時排除
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
public @interface MyExclus {

}

值為空也序列化

public static Gson getGson(String[] strs) {
        return new GsonBuilder().serializeNulls().create();
}

值為null轉換為”“

public static Gson getGson(String[] strs) {
        return new GsonBuilder()
                .registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory<Object>())
                .create();
}

/**
*YC 
*2017年8月1日 下午4:41:21
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.adapter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;

/**
 * @author YC 將null轉換為""工廠介面卡
 */
public class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory {
    @SuppressWarnings({ "unchecked", "hiding" })
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        Class<T> rawType = (Class<T>) type.getRawType();
        if (rawType != String.class) {
            return null;
        }
        return (TypeAdapter<T>) new StringNullAdapter();
    }
}

/**
*YC 
*2017年8月1日 下午4:36:50
* <p>Description: </p> 
*/
package com.huiw.core.uic.common.adapter;

import java.io.IOException;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

/**
 * @author YC 將null轉換為""介面卡
 */
public class StringNullAdapter extends TypeAdapter<String> {
    @Override
    public String read(JsonReader reader) throws IOException {
        // TODO Auto-generated method stub
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return "";
        }
        return reader.nextString();
    }

    @Override
    public void write(JsonWriter writer, String value) throws IOException {
        // TODO Auto-generated method stub
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }

}

排除策略

public static Gson getGson() {
        return new GsonBuilder().setExclusionStrategies(new AnnotationExclusion()).create();
}

@你這個只能將String型別的null轉為空字串啊,如果是Int、Long、ArrayList呢?那豈不是要寫全部的資料型別,如果不管是什麼型別都轉換為空字串,這個就不行了,比如Int型別的null只能轉為Int不能轉為空字串。

public class Person implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private String name;
    private Integer age;
    //User類似Person物件有name、age欄位
    private List<User> list;
        //set、get略
}

public static void main(String[] args) {
        // 獲取PerfectGson物件
        Gson gson = PerfectGson.getGson();
        // 例項化一個人(name[String]、age[Intager]、list[List<User>]),未賦值
        Person person = new Person();
        // PerfectGson轉換出一個值為空的json串
        gson = gson.fromJson(gson.toJson(person), new TypeToken<Person>() {
        }.getType());
        // 模擬spring MVC的controller層返回給ajax的資料
        System.out.println(JSONObject.fromObject(gson));
    }

//控制檯:
//{"name":"","age":0,"list":[]}

相關推薦

gson序列化物序列null轉換""排除策略

修改記錄 日期 提出 說明 2018-03-23 20:08 @bxl049 AnnotationExclusion、FieldExclusion這兩哥類程式碼也沒有貼呀 2018-01-03 17:24 @

mysql查詢欄位字串時給預設 2null時給一預設

1、 case when post_ask_pay.price='' then 10 else post_ask_pay.price end as priceSELECT distinct post_ask_pay.user_id as ask_user_id,post_

Kryo序列化物字串(Base64加密)

1、Kryo的簡介 Kryo 是一個快速高效的Java物件圖形序列化框架,主要特點是效能、高效和易用。該專案用來序列化物件到檔案、資料庫或者網路。       Kryo的序列化及反序列速度很快,據說很多大公司都在用。我在把物件序列化都轉換成了字串形式,是為了把物件儲存到

ayer.prompt 怎樣讓輸入可以向下執行

字數 value tips title 方案 layer func fly () http://fly.layui.com/jie/4227/ layer.prompt({title: ‘輸入任何口令,並確認‘,formType: 1, //prompt風格,支持0-2

redis redistemplate序列化物配置

  @Configuration public class RedisConfig { /** * 重寫Redis序列化方式,使用Json方式: * 當我們的資料儲存到Redis的時候,我們的鍵(key)和值(value)都是通過Spring提供的Seria

Android中Serializable和Parcelable序列化物詳解

學習內容: 1.序列化的目的 2.Android中序列化的兩種方式 3.Parcelable與Serializable的效能比較 4.Android中如何使用Parcelable進行序列化操作 5.Parcelable的工作原理 6.相關例項   1.序列化

Android Serializable和Parcelable序列化物詳解

轉載:https://www.cnblogs.com/yezhennan/p/5527506.html 學習內容: 1.序列化的目的 2.Android中序列化的兩種方式 3.Parcelable與Serializable的效能比較 4.Android中如何使用Parcelabl

oracle+.net 資料序列化物時報錯"物件必須實現 IConvertible"介面解決方法

oracle+.net 資料序列化物件時報錯”物件必須實現 IConvertible”介面解決方法 見圖: 具體錯誤就是這樣 寫過序列化的都知道 資料系列化失敗無非欄位和資料型別有問題 只是

HTML公用函式——日期的時候設定預設

日期為空的時候,傳輸資料報錯,為日期設定預設值,傳輸資料到後臺  function ChangeNullDate(cellval) { if (cellval) { return cellval;

Spring MVC中 Json序列化物例項的問題和兩個辦法

情況是這樣的: HTTP請求中,將一個類的例項直接JSON成文字,返回給客戶的端的辦法。 系統:ContOS ,IDE:intellij Spring:4.3.6 Json:1.9.13 如果要將一個類的例項直接返回給HTTP請求的客戶端,是沒辦法的。這樣做的結果是500錯

Hessian RPC示例和基於Http請求的Hessian序列化物傳輸

本文主要介紹兩個案例,第一個是使用Hessian來實現遠端過程呼叫,第二個是通過Hessian提供的二進位制RPC協議進行和Servlet進行資料互動,Hessian本身即是基於Http的RPC實現。 案例一: 1.準備工作 這裡建立一個Maven專案,其中包含四個模組,父模組(僅用來聚合其它模組,

mysql儲存過程判斷不和不,查詢結果賦變數

直接看例子,判斷為空是is null delimiter // create procedure proc__pre_activity_scan() begin    declare p_tid int(10);    set @p_tid=(select tid fro

EL表示式判斷Map是否和map的取

action中的程式碼private Map<String, String> msgs = new HashMap<String, String>msgs.put("loginError", "驗證碼錯誤");jsp頁面中的程式碼:<script type="text/javas

Android下利用SharePreference儲存序列化物的方法

在android下做持久化的資料儲存,大部分是用到了sqlite資料庫或者sharepreference。當然我們為了圖方便,少寫sql語句,大部分都是用ORM形式的開源資料庫框架,例如greendao和cupboard或者dao4,但是在一般小型儲存系統中,我還是比較喜歡

mysql刪除欄位的資料 mysql中空NULL的區別

空值與NULL的區別   我們先來理解mysql中空值與NULL的區別是什麼吧   一些剛剛接觸MySQL的孩子,經常會錯誤的認為NULL與空字串’ ’是相同的。這看似是一件不重要的事情,但是在MySQL中,這兩者是完全不同的。NULL是指沒有值,而”則表示值是存在的,

序列化物壓縮和解壓縮byte陣列例項

public byte[] serialize(List<String> result) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Java

Spring註解配置初始化物

Spring註解配置初始化物件(<bean>): spring中使用註解配置物件前,要在配置檔案中配置context:component-scan 標籤 告訴spring框架,配置了註解的類的位置 配置檔案applicationContext.xml: <

[轉]dubbo序列化物的一個坑

最近工作中遇見了一個小問題,在此記錄一下,大致是這樣的,有一父類,有一個屬性traceId,主要是記錄日誌號,這樣可以把所有日誌串起來,利於排查問題,所有的pojo物件繼承於此,但是其中一同事在子類pojo中也增加了這一個屬性,在消費者端給traceId設定了值

Android中傳送序列化物出現的ClassNotFoundException解決辦法

http://waynehu16.iteye.com/blog/1530760 最近在做課程設計,老師要求是基於Android上的wifi通訊的,之前沒事的時候寫過一個套接字程式設計的,完成了一個類似於聊天工具的功能。於是就想著改改,湊合著用用交上去。沒想到在寫的時候發

【C#】解決進行反序列時出錯:。InnerException 訊息是“反序列化物 屬於型別 System.String 時出現錯誤。讀取 XML 資料時,超出最大字串內容長度配額 (8192)。

解決:.NET進行反序列化時出錯:。InnerException 訊息是“反序列化物件 屬於型別 System.String 時出現錯誤。讀取 XML 資料時,超出最大字串內容長度配額 (8192)