Example usage for com.google.gson GsonBuilder registerTypeHierarchyAdapter

List of usage examples for com.google.gson GsonBuilder registerTypeHierarchyAdapter

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder registerTypeHierarchyAdapter.

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter) 

Source Link

Document

Configures Gson for custom serialization or deserialization for an inheritance type hierarchy.

Usage

From source file:cc.kave.commons.utils.json.JsonUtils.java

License:Apache License

private static GsonBuilder createBuilder() {
    GsonBuilder gb = new GsonBuilder();

    // add support for new Java 8 date/time framework
    gb.registerTypeHierarchyAdapter(LocalDateTime.class, new LocalDateTimeConverter());
    Converters.registerAll(gb);//from  www  .jav a2 s. c  o m
    gb.registerTypeAdapter(Duration.class, new DurationConverter());

    GsonUtil.addTypeAdapters(gb);

    registerNames(gb);
    registerSSTHierarchy(gb);
    registerEventHierarchy(gb);

    gb.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    gb.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);

    return gb;
}

From source file:co.aurasphere.botmill.fb.internal.util.json.FbBotMillJsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats./* ww w . jav  a2 s.  c o  m*/
 * 
 * @return the current instance of Gson.
 */
private static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();

        // Serializes enums as lower-case.
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumLowercaseSerializer());

        // Serializes calendar in format YYYY-MM-DDThh:mm.
        builder.registerTypeHierarchyAdapter(Calendar.class, new CalendarSerializer());

        // Deserializes payloads from interface.
        builder.registerTypeAdapter(Attachment.class, new AttachmentDeserializer());

        // Serializes/deserializes buttons from interface.
        builder.registerTypeAdapter(Button.class, new ButtonSerializer());

        // Deserializes incoming messages from interface.
        builder.registerTypeAdapter(IncomingMessage.class, new IncomingMessageDeserializer());

        // Deserializes timestamp as Calendar.
        builder.registerTypeAdapter(Calendar.class, new CalendarFromTimestampJsonDeserializer());

        gson = builder.create();
    }
    return gson;
}

From source file:co.aurasphere.botmill.fb.internal.util.json.JsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats./*from   w  w w .j a  v  a 2 s  .  c  om*/
 * 
 * @return the current instance of Gson.
 */
private static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();

        // Serializes enums as lower-case.
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumLowercaseSerializer());

        // Serializes calendar in format YYYY-MM-DDThh:mm.
        builder.registerTypeHierarchyAdapter(Calendar.class, new CalendarSerializer());

        // Deserializes payloads from interface.
        builder.registerTypeAdapter(Attachment.class, new AttachmentDeserializer());

        // Deserializes buttons from interface.
        builder.registerTypeAdapter(Button.class, new ButtonDeserializer());

        builder.registerTypeAdapter(List.class, new PolimorphicalListSerializer<List<Button>>());

        // Deserializes incoming messages from interface.
        builder.registerTypeAdapter(IncomingMessage.class, new IncomingMessageDeserializer());

        gson = builder.create();
    }
    return gson;
}

From source file:co.aurasphere.botmill.kik.util.json.JsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats./*from   ww  w.  j  av a 2 s . com*/
 * 
 * @return the current instance of Gson.
 */
public static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();
        // Serializes enums as lower-case.
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumLowercaseSerializer());

        builder.registerTypeHierarchyAdapter(MessageCallback.class, new IncomingMessagesDeserializer());
        //   EnumDeserializer
        builder.registerTypeHierarchyAdapter(Calendar.class, new CalendarSerializer());

        gson = builder.create();
    }
    return gson;
}

From source file:co.aurasphere.botmill.skype.util.json.JsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats./*from   ww  w  .j  av a 2  s. c  o m*/
 * 
 * @return the current instance of Gson.
 */
public static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();
        // Serializes enums as lower-case.
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumLowercaseSerializer());
        builder.registerTypeHierarchyAdapter(Calendar.class, new CalendarSerializer());

        gson = builder.create();
    }
    return gson;
}

From source file:co.aurasphere.botmill.telegram.internal.util.json.JsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Telegram
 * formats.//w  ww  .j  a  va2 s.  c  o  m
 * 
 * @return the current instance of Gson.
 */
private static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();

        //         // Serializes enums as lower-case.
        //         builder.registerTypeHierarchyAdapter(Enum.class,
        //               new EnumLowercaseSerializer());
        //
        //         // Serializes calendar in format YYYY-MM-DDThh:mm.
        builder.registerTypeHierarchyAdapter(Calendar.class, new CalendarFromTimestampJsonDeserializer());

        gson = builder.create();
    }
    return gson;
}

From source file:co.aurasphere.botmill.util.JsonUtils.java

License:Open Source License

/**
 * Initializes the current Gson object if null and returns it. The Gson
 * object has custom adapters to manage datatypes according to Facebook
 * formats.//from  www  .  j  a va2  s .  c o m
 * 
 * @return the current instance of Gson.
 */
public static Gson getGson() {
    if (gson == null) {
        // Creates the Gson object which will manage the information
        // received
        GsonBuilder builder = new GsonBuilder();
        // Serializes enums as lower-case.
        builder.registerTypeHierarchyAdapter(Enum.class, new EnumLowercaseSerializer());
        builder.registerTypeAdapter(Entity.class, new EntityValueDeserializer());
        gson = builder.create();
    }
    return gson;
}

From source file:com.expensify.testframework.SubmitResultContainer.java

License:Microsoft Public License

public static String RawStringify(ResultBase result) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();/*from  w  ww  . j  a  v  a2 s  .c o  m*/
    gsonBuilder.serializeNulls();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    gsonBuilder.disableHtmlEscaping();
    gsonBuilder.registerTypeHierarchyAdapter(ResultBase.class, new ResultSerializer());
    String resultJson = gson.toJson(result);
    resultJson = hackResultJsonOrder(resultJson);
    return resultJson;
}

From source file:com.google.api.ads.adwords.keywordoptimizer.api.JsonUtil.java

License:Open Source License

/**
 * Initializes Gson to convert objects to and from JSON. This method customizes a "plain" Gson by
 * adding appropriate exclusions strategies / adapters as needed in this project for a "pretty"
 * output. // w  w  w  .j av a 2 s  . co  m
 */
private static Gson initGson(boolean prettyPrint) {
    GsonBuilder builder = new GsonBuilder();

    // Exclude superclasses.
    ExclusionStrategy superclassExclusionStrategy = new SuperclassExclusionStrategy();
    builder.addDeserializationExclusionStrategy(superclassExclusionStrategy);
    builder.addSerializationExclusionStrategy(superclassExclusionStrategy);

    // Exclude underscore fields in client lib objects.
    ExclusionStrategy underscoreExclusionStrategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes field) {
            if (field.getName().startsWith("_")) {
                return true;
            }

            return false;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };
    builder.addDeserializationExclusionStrategy(underscoreExclusionStrategy);
    builder.addSerializationExclusionStrategy(underscoreExclusionStrategy);

    // Render KeywordCollection as an array of KeywordInfos.
    builder.registerTypeAdapter(KeywordCollection.class, new JsonSerializer<KeywordCollection>() {
        @Override
        public JsonElement serialize(KeywordCollection src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonArray out = new JsonArray();
            for (KeywordInfo info : src.getListSortedByScore()) {
                out.add(context.serialize(info));
            }
            return out;
        }
    });
    // Render Money as a primitive.
    builder.registerTypeAdapter(Money.class, new JsonSerializer<Money>() {
        @Override
        public JsonElement serialize(Money src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonElement out = new JsonPrimitive(src.getMicroAmount() / 1000000);
            return out;
        }
    });
    // Render Keyword in a simple way.
    builder.registerTypeAdapter(Keyword.class, new JsonSerializer<Keyword>() {
        @Override
        public JsonElement serialize(Keyword src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("text", src.getText());
            out.addProperty("matchtype", src.getMatchType().toString());
            return out;
        }
    });
    // Render Throwable in a simple way (for all subclasses).
    builder.registerTypeHierarchyAdapter(Throwable.class, new JsonSerializer<Throwable>() {
        @Override
        public JsonElement serialize(Throwable src, java.lang.reflect.Type typeOfSrc,
                JsonSerializationContext context) {
            JsonObject out = new JsonObject();
            out.addProperty("message", src.getMessage());
            out.addProperty("type", src.getClass().getName());

            JsonArray stack = new JsonArray();
            for (StackTraceElement stackTraceElement : src.getStackTrace()) {
                JsonObject stackElem = new JsonObject();
                stackElem.addProperty("file", stackTraceElement.getFileName());
                stackElem.addProperty("line", stackTraceElement.getLineNumber());
                stackElem.addProperty("method", stackTraceElement.getMethodName());
                stackElem.addProperty("class", stackTraceElement.getClassName());
                stack.add(stackElem);
            }
            out.add("stack", stack);

            if (src.getCause() != null) {
                out.add("cause", context.serialize(src.getCause()));
            }
            return out;
        }
    });

    if (prettyPrint) {
        builder.setPrettyPrinting();
    }

    return builder.create();
}

From source file:com.google.devtools.kythe.util.JsonUtil.java

License:Open Source License

/**
 * Registers type adapters for Java protobuf types (including ByteStrings and byte[]) that matches
 * Go's JSON encoding/decoding.//from   w w  w.  ja  va  2 s . co  m
 */
public static GsonBuilder registerProtoTypes(GsonBuilder builder) {
    return builder.registerTypeHierarchyAdapter(ProtocolMessageEnum.class, new ProtoEnumTypeAdapter())
            .registerTypeHierarchyAdapter(GeneratedMessage.class, new ProtoTypeAdapter())
            .registerTypeHierarchyAdapter(ByteString.class, new ByteStringTypeAdapter())
            .registerTypeAdapter(byte[].class, new ByteArrayTypeAdapter());
}