cn.teamlab.wg.framework.struts2.json.JsonSerializerBuilder.java Source code

Java tutorial

Introduction

Here is the source code for cn.teamlab.wg.framework.struts2.json.JsonSerializerBuilder.java

Source

/**
 * Copyright 2014 Cenobit Technologies Inc. http://cenobit.es/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.teamlab.wg.framework.struts2.json;

import java.lang.reflect.Type;
import java.util.Date;
import java.util.Set;

import org.joda.time.DateTime;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.internal.bind.DateTypeAdapter;

import cn.teamlab.wg.framework.util.date.DateFormatter;

public class JsonSerializerBuilder {

    public static GsonBuilder builder() {
        return new GsonBuilder() //
                .disableHtmlEscaping().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                    @Override
                    public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                        if (src == src.longValue())
                            return new JsonPrimitive(src.longValue());
                        return new JsonPrimitive(src);
                    }
                }).registerTypeAdapter(Date.class, new DateTypeAdapter())
                .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {

                    @Override
                    public JsonElement serialize(DateTime arg0, Type arg1, JsonSerializationContext arg2) {
                        return new JsonPrimitive(arg0.toString(DateFormatter.SDF_YMDHMS6));
                    }
                });
    }

    public static Gson create() {
        return builder() //
                .create();
    }

    public static Gson create(Set<String> fieldsToExclude, Class<?>... classes) {
        return builder() //
                .setExclusionStrategies(new JsonSerializerExclusionStrategy(fieldsToExclude, classes)) //
                .create();
    }
}