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:com.quix.aia.cn.imo.rest.AddressBookRest.java

License:Open Source License

@GET
@Path("/getCCTestResults")
@Produces(MediaType.APPLICATION_JSON)//from   w w  w  .  j av a2  s  . co  m
public Response getCCTestResults(@Context HttpServletRequest request) {
    log.log(Level.INFO, "Address Book --> getCCTestResults ");
    LogsMaintenance logsMain = new LogsMaintenance();
    ContractDetail contractDetail = new ContractDetail();
    AddressBook addressBook;
    GsonBuilder builder = new GsonBuilder();
    AddressBookMaintenance addressBookMaintenance = new AddressBookMaintenance();

    Gson googleJson = null;
    MsgBeans beans = new MsgBeans();
    AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance();
    List<AddressBook> addressBookList = new ArrayList();
    String jsonString = "";
    try {

        builder.registerTypeHierarchyAdapter(byte[].class, new JsonSerializer<byte[]>() {
            public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
                return new JsonPrimitive(Base64.encodeBase64String(src));
            }
        });

        googleJson = builder.setDateFormat("yyyy-MM-dd HH:mm:ss").create();

        log.log(Level.INFO, "Address Book --> fetching Information ... ");
        addressBook = new AddressBook();
        String candidateCode = request.getParameter("candidateCode");
        candidateCode = null != candidateCode ? candidateCode : "";
        String agentId = request.getParameter("agentId");
        agentId = null != agentId ? agentId : "";

        //addressBook = addressBookMaintenance.getAddressBook(candidateCode, agentId);
        String[] fetchFields = { "ccTestResult", "ccTestResultDate" };
        String[] conditionFieldName = { "addressCode", "agentId" };
        String[] conditionFieldValue = { candidateCode, agentId };
        List<Object[]> list = addressBookMaintenance.getAddressBookSelectedField(fetchFields,
                conditionFieldName, conditionFieldValue);

        addressBookMaintenance.updateAddressBookStatus("6/9", conditionFieldName, conditionFieldValue);
        if (!list.isEmpty()) {
            Object[] obj = list.get(0);
            addressBook.setCcTestResult("" + obj[0]);
            addressBook.setCcTestResultDate((Date) obj[1]);
        }

        jsonString += "[{\"CCTestResult\":\"" + addressBook.getCcTestResult() + "\",\"Date\":\""
                + LMSUtil.convertDateToyyyymmddhhmmssDashedString(addressBook.getCcTestResultDate()) + "\"}]";
        // Convert the object to a JSON string
        log.log(Level.INFO, "Address Book --> Information fetched successfully... ");

        return Response.status(200).entity(jsonString).build();
    } catch (Exception e) {
        beans.setCode("500");
        beans.setMassage(
                "Something wrong happens, please contact administrator. Error Message : " + e.getMessage());
        auditTrailMaint.insertAuditTrail(
                new AuditTrail("Rest", AuditTrail.MODULE_ADDRESS_BOOK, AuditTrail.FUNCTION_FAIL, "FAILED"));

        log.log(Level.SEVERE, "Address Book --> Error in fetching Record.");
        log.log(Level.SEVERE, e.getMessage());
        e.printStackTrace();
        StringWriter errors = new StringWriter();
        e.printStackTrace(new PrintWriter(errors));
        logsMain.insertLogs("AddressBookRest", Level.SEVERE + "", errors.toString());

        return Response.status(200).entity(googleJson.toJson(beans)).build();
    } finally {
        addressBookList.clear();
        auditTrailMaint = null;
        addressBookMaintenance = null;
        jsonString = null;
        beans = null;
        builder = null;
        googleJson = null;
        System.gc();
    }
}

From source file:com.shazam.shazamcrest.matcher.GsonProvider.java

License:Apache License

private static void registerMapSerialisation(final GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeHierarchyAdapter(Map.class, new JsonSerializer<Map>() {
        @Override/*from  w  ww.  ja v  a  2 s .c  o  m*/
        public JsonElement serialize(Map map, Type type, JsonSerializationContext context) {
            Gson gson = gsonBuilder.create();

            ArrayListMultimap<String, Object> objects = mapObjectsByTheirJsonRepresentation(map, gson);
            return arrayOfObjectsOrderedByTheirJsonRepresentation(gson, objects, map);
        }
    });
}

From source file:com.shazam.shazamcrest.matcher.GsonProvider.java

License:Apache License

private static void registerSetSerialisation(final GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeHierarchyAdapter(Set.class, new JsonSerializer<Set>() {
        @Override//from  w w w  . j  a  v  a 2  s.  c o  m
        public JsonElement serialize(Set set, Type type, JsonSerializationContext context) {
            Gson gson = gsonBuilder.create();

            Set<Object> orderedSet = orderSetByElementsJsonRepresentation(set, gson);
            return arrayOfObjectsOrderedByTheirJsonRepresentation(gson, orderedSet);
        }
    });
}

From source file:com.thoughtworks.go.server.web.JsonRenderer.java

License:Apache License

private static Gson gsonBuilder(final GoRequestContext requestContext) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapter(JsonUrl.class, (JsonSerializer<JsonUrl>) (src, typeOfSrc, context) -> {
        if (requestContext == null) {
            return new JsonPrimitive(src.getUrl());
        } else {/*w ww .  j  av a 2s. co m*/
            return new JsonPrimitive(requestContext.getFullRequestPath() + src.getUrl());
        }
    });

    builder.registerTypeHierarchyAdapter(MessageSourceResolvable.class,
            (JsonSerializer<MessageSourceResolvable>) (src, typeOfSrc, context) -> {
                if (requestContext == null) {
                    return new JsonPrimitive(src.getDefaultMessage());
                } else {
                    return new JsonPrimitive(requestContext.getMessage(src));
                }
            });

    builder.serializeNulls();
    return builder.create();
}

From source file:com.udeyrishi.androidelasticsearchdatamanager.JsonFormatter.java

License:Apache License

/**
 * Gets the {@link Gson} object configured with the settings of this {@link JsonFormatter}.
 *
 * @return The properly configured {@link Gson}.
 *//*from  w  ww .  j  av a 2 s  .  c om*/
public Gson getGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();

    if (getUsePrettyJson()) {
        gsonBuilder.setPrettyPrinting();
    }

    if (getUseExplicitExposeAnnotation()) {
        gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    }

    // Register custom serializers
    for (Map.Entry<Class<?>, JsonSerializer<?>> entry : serializers.entrySet()) {
        gsonBuilder.registerTypeHierarchyAdapter(entry.getKey(), entry.getValue());
    }

    for (Map.Entry<Class<?>, JsonDeserializer<?>> entry : deserializers.entrySet()) {
        gsonBuilder.registerTypeHierarchyAdapter(entry.getKey(), entry.getValue());
    }

    return gsonBuilder.create();
}

From source file:com.vaadin.addon.charts.model.AbstractConfigurationObject.java

/**
 * Returns default GSON builder for configuration serializer.
 *//*from   w w  w. j av a  2 s.c om*/
public static GsonBuilder createGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();
    // uncomment if you wish to debug generated json
    builder.setPrettyPrinting();
    builder.registerTypeHierarchyAdapter(ChartEnum.class, new ChartEnumSerializer());
    builder.registerTypeHierarchyAdapter(SolidColor.class, new SolidColorSerializer());
    builder.registerTypeHierarchyAdapter(AxisList.class, new AxisListSerializer());
    builder.registerTypeHierarchyAdapter(PaneList.class, new PaneListSerializer());
    builder.registerTypeAdapter(ContainerDataSeries.class, new ContainerDataSeriesSerializer());
    builder.registerTypeAdapterFactory(new DataSeriesItemTypeAdapterFactory());
    builder.registerTypeAdapterFactory(new AbstractSeriesTypeAdapterFactory());
    builder.registerTypeAdapterFactory(new TitleTypeAdapterFactory());
    return builder;
}

From source file:com.vmware.dcp.common.serialization.JsonMapper.java

License:Open Source License

private static void registerCommonGsonTypeAdapters(GsonBuilder bldr) {
    bldr.registerTypeAdapter(ObjectMapTypeConverter.TYPE, ObjectMapTypeConverter.INSTANCE);
    bldr.registerTypeAdapter(InstantConverter.TYPE, InstantConverter.INSTANCE);
    bldr.registerTypeAdapter(ZonedDateTimeConverter.TYPE, ZonedDateTimeConverter.INSTANCE);
    bldr.registerTypeHierarchyAdapter(byte[].class, new ByteArrayToBase64TypeAdapter());
    bldr.registerTypeAdapter(RequestRouteConverter.TYPE, RequestRouteConverter.INSTANCE);
}

From source file:edu.eci.arsw.umlcolaborativo.services.InMemoryElementsRedis.java

/**
 * Constructor de elementos de redis//from  w ww . j a  v  a  2s. co m
 * @throws edu.eci.arsw.umlcolaborativo.entities.ProyectoExcepcion
 */
public InMemoryElementsRedis() throws ProyectoExcepcion {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeHierarchyAdapter(Elemento.class, new InterfaceAdapter<Elemento>());
    gson = builder.create();
    //gson = new Gson();  
    jsonParser = new JsonParser();
    cargarElementos();
    System.out.println("Cargo los elementos");
}

From source file:edu.eci.arsw.umlcolaborativo.services.InMemoryRelationsRedis.java

/**
 * Constructor de las memoria de relaciones de redis
 *///  w  ww.j a v  a2 s . co m
public InMemoryRelationsRedis() {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeHierarchyAdapter(Relacion.class, new InterfaceAdapter<Relacion>());
    gson = builder.create();
    //gson = new Gson();  
    jsonParser = new JsonParser();
}

From source file:net.kyori.text.serializer.gson.GsonComponentSerializer.java

License:MIT License

/**
 * Populate a builder with our serializers.
 *
 * @param builder the gson builder/* ww w .j  a v a  2 s.  c  om*/
 * @return the gson builder
 */
public static @NonNull GsonBuilder populate(final @NonNull GsonBuilder builder) {
    builder.registerTypeHierarchyAdapter(Component.class, INSTANCE)
            .registerTypeAdapter(Style.class, StyleSerializer.INSTANCE)
            .registerTypeAdapter(ClickEvent.Action.class,
                    new NameMapSerializer<>("click action", ClickEvent.Action.NAMES))
            .registerTypeAdapter(HoverEvent.Action.class,
                    new NameMapSerializer<>("hover action", HoverEvent.Action.NAMES))
            .registerTypeAdapter(TextColorWrapper.class, new TextColorWrapper.Serializer())
            .registerTypeAdapter(TextColor.class, new NameMapSerializer<>("text color", TextColor.NAMES))
            .registerTypeAdapter(TextDecoration.class,
                    new NameMapSerializer<>("text decoration", TextDecoration.NAMES))
            .registerTypeHierarchyAdapter(BlockNbtComponent.Pos.class, BlockNbtComponentPosSerializer.INSTANCE);
    return builder;
}