2025-02-17

在客戶端和服務端交互使用JSON的時候,有byte[]類型的數據時候,JSON字符串會成倍增長,每個字節都會轉變成0x..的字符串 ,增加瞭數據交互的文件傳輸量。


/*
 * GOSN常用類
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */ 
package org.brtx.tools; 
 
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.JsonPrimitive; 
import com.google.gson.JsonSerializationContext; 
import com.google.gson.JsonSerializer; 
import java.io.IOException; 
import java.lang.reflect.Type; 
import java.sql.Timestamp; 
import java.text.DateFormat; 
import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import sun.misc.BASE64Decoder; 
import sun.misc.BASE64Encoder; 
 
/**
 *toJson的相關方法
 * @author Administrator
 */ 
public class GSONTOOLS { 
 
    /**
     * 獲取GSON轉換模式,默認日期格式為“yyyy-MM-dd HH:mm:ss”
     * @return
     */ 
    public static Gson getGson() { 
        GsonBuilder builder = new GsonBuilder(); 
        // 不轉換沒有 @Expose 註解的字段 
        builder.excludeFieldsWithoutExposeAnnotation(); 
        builder.registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create(); 
        builder.registerTypeHierarchyAdapter(byte[].class, new ByteArrayTypeAdapter()).create(); 
        Gson gson = builder.create(); 
        return gson; 
    } 
 
    /**
     * 獲取GSON轉換模式,設置時間格式為dataFat
     * @param dataFat 時間格式
     * @return
     */ 
    public static Gson getGson(String dataFat) { 
        GsonBuilder builder = new GsonBuilder(); 
        // 不轉換沒有 @Expose 註解的字段 
        builder.excludeFieldsWithoutExposeAnnotation(); 
        builder.registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat(dataFat).create(); 
        builder.registerTypeHierarchyAdapter(byte[].class, new ByteArrayTypeAdapter()).create(); 
        Gson gson = builder.create(); 
        return gson; 
    } 

 
/**
 * json包含日期類型的時候的處理方法
 * @author Administrator
 */ 
class TimestampTypeAdapter implements JsonSerializer<Timestamp>, JsonDeserializer<Timestamp> { 
 
    private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
 
    public JsonElement serialize(Timestamp src, Type arg1, JsonSerializationContext arg2) { 
        String dateFormatAsString = format.format(new Date(src.getTime())); 
        return new JsonPrimitive(dateFormatAsString); 
    } 
 
    public Timestamp deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
        if (!(json instanceof JsonPrimitive)) { 
            throw new JsonParseException("The date should be a string value"); 
        } 
 
        try { 
            Date date = format.parse(json.getAsString()); 
            return new Timestamp(date.getTime()); 
        } catch (ParseException e) { 
            throw new JsonParseException(e); 
        } 
    } 

 
class ByteArrayTypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { 
 
    public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { 
        BASE64Encoder encode = new BASE64Encoder(); 
        String base64 = encode.encode(src); 
        return new JsonPrimitive(base64); 
    } 
 
    public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 
        if (!(json instanceof JsonPrimitive)) { 
            throw new JsonParseException("The date should be a string value"); 
        } 
        try { 
            BASE64Decoder decode = new BASE64Decoder(); 
            byte[] base64 = decode.decodeBuffer(json.getAsString()); 
            return base64; 
        } catch (IOException ex) { 
        } 
        return null; 
    } 

使用這個類將byte[]通過base64進行壓縮,降低JSON的數據量4倍左右。

摘自 狐貍愛上貓—-JAVA LINUX SWING EXTJS AJAX專欄

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *