001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.http.converter.json; 018 019import java.lang.reflect.Type; 020 021import com.google.gson.GsonBuilder; 022import com.google.gson.JsonDeserializationContext; 023import com.google.gson.JsonDeserializer; 024import com.google.gson.JsonElement; 025import com.google.gson.JsonPrimitive; 026import com.google.gson.JsonSerializationContext; 027import com.google.gson.JsonSerializer; 028 029import org.springframework.util.Base64Utils; 030 031/** 032 * A simple utility class for obtaining a Google Gson 2.x {@link GsonBuilder} 033 * which Base64-encodes {@code byte[]} properties when reading and writing JSON. 034 * 035 * @author Juergen Hoeller 036 * @author Roy Clarkson 037 * @since 4.1 038 * @see GsonFactoryBean#setBase64EncodeByteArrays 039 * @see org.springframework.util.Base64Utils 040 */ 041public abstract class GsonBuilderUtils { 042 043 /** 044 * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]} 045 * properties when reading and writing JSON. 046 * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via 047 * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which 048 * serializes a {@code byte[]} property to and from a Base64-encoded String 049 * instead of a JSON array. 050 */ 051 public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() { 052 GsonBuilder builder = new GsonBuilder(); 053 builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter()); 054 return builder; 055 } 056 057 058 private static class Base64TypeAdapter implements JsonSerializer<byte[]>, JsonDeserializer<byte[]> { 059 060 @Override 061 public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) { 062 return new JsonPrimitive(Base64Utils.encodeToString(src)); 063 } 064 065 @Override 066 public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) { 067 return Base64Utils.decodeFromString(json.getAsString()); 068 } 069 } 070 071}