List of usage examples for com.google.gson GsonBuilder registerTypeHierarchyAdapter
@SuppressWarnings({ "unchecked", "rawtypes" }) public GsonBuilder registerTypeHierarchyAdapter(Class<?> baseType, Object typeAdapter)
From source file:com.haulmont.cuba.core.app.serialization.EntitySerialization.java
License:Apache License
protected Gson createGsonForSerialization(@Nullable View view, EntitySerializationOption... options) { GsonBuilder gsonBuilder = new GsonBuilder(); if (ArrayUtils.contains(options, EntitySerializationOption.PRETTY_PRINT)) { gsonBuilder.setPrettyPrinting(); }//from ww w . j a va 2s . c om gsonBuilder.registerTypeHierarchyAdapter(Entity.class, new EntitySerializer(view, options)) .registerTypeHierarchyAdapter(Date.class, new DateSerializer()).create(); if (ArrayUtils.contains(options, EntitySerializationOption.SERIALIZE_NULLS)) { gsonBuilder.serializeNulls(); } return gsonBuilder.create(); }
From source file:com.ibm.common.activitystreams.internal.GsonWrapper.java
License:Apache License
/** * Method initGsonBuilder./*from w ww . ja v a 2 s. com*/ * @param builder Builder * @return GsonBuilder */ private static GsonBuilder initGsonBuilder(Builder builder, Schema schema, ASObjectAdapter base, Iterable<AdapterEntry<?>> adapters) { GsonBuilder gson = new GsonBuilder() .registerTypeHierarchyAdapter(TypeValue.class, new TypeValueAdapter(schema)) .registerTypeHierarchyAdapter(LinkValue.class, new LinkValueAdapter(schema)) .registerTypeHierarchyAdapter(Iterable.class, ITERABLE) .registerTypeHierarchyAdapter(ASObject.class, base) .registerTypeHierarchyAdapter(Collection.class, base) .registerTypeHierarchyAdapter(Activity.class, base).registerTypeHierarchyAdapter(NLV.class, NLV) .registerTypeHierarchyAdapter(ActionsValue.class, ACTIONS) .registerTypeHierarchyAdapter(Optional.class, OPTIONAL) .registerTypeHierarchyAdapter(Range.class, RANGE).registerTypeHierarchyAdapter(Table.class, TABLE) .registerTypeHierarchyAdapter(LazilyParsedNumber.class, NUMBER) .registerTypeHierarchyAdapter(LazilyParsedNumberComparable.class, NUMBER) .registerTypeHierarchyAdapter(ReadableDuration.class, DURATION) .registerTypeHierarchyAdapter(ReadablePeriod.class, PERIOD) .registerTypeHierarchyAdapter(ReadableInterval.class, INTERVAL) .registerTypeAdapter(Activity.Status.class, forEnum(Activity.Status.class, Activity.Status.OTHER)) .registerTypeAdapter(Date.class, DATE).registerTypeAdapter(DateTime.class, DATETIME) .registerTypeAdapter(MediaType.class, MIMETYPE) .registerTypeHierarchyAdapter(Multimap.class, MULTIMAP); for (AdapterEntry<?> entry : adapters) { if (entry.hier) gson.registerTypeHierarchyAdapter(entry.type, entry.adapter != null ? entry.adapter : base); else gson.registerTypeAdapter(entry.type, entry.adapter != null ? entry.adapter : base); } return gson; }
From source file:com.jd.survey.service.util.JsonHelperService.java
License:Open Source License
public String serializeSurveyDefinition(SurveyDefinition surveyDefinition) { try {/* w ww .ja v a2 s. c o m*/ GsonBuilder gsonBuilder = new GsonBuilder(); //set up the fields to skip in the serialization gsonBuilder = gsonBuilder.setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipClass(Class<?> clazz) { return false; } @Override public boolean shouldSkipField(FieldAttributes f) { boolean skip = (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("id")) || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("version")) || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("department")) || (f.getDeclaringClass() == SurveyDefinition.class && f.getName().equals("users")) || (f.getDeclaringClass() == SurveyDefinitionPage.class && f.getName().equals("id")) || (f.getDeclaringClass() == SurveyDefinitionPage.class && f.getName().equals("surveyDefinition")) || (f.getDeclaringClass() == Question.class && f.getName().equals("id")) || (f.getDeclaringClass() == Question.class && f.getName().equals("version")) || (f.getDeclaringClass() == Question.class && f.getName().equals("page")) || (f.getDeclaringClass() == Question.class && f.getName().equals("optionsList")) || (f.getDeclaringClass() == Question.class && f.getName().equals("rowLabelsList")) || (f.getDeclaringClass() == Question.class && f.getName().equals("columnLabelsList")) || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("id")) || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("version")) || (f.getDeclaringClass() == QuestionOption.class && f.getName().equals("question")) || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("id")) || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("version")) || (f.getDeclaringClass() == QuestionRowLabel.class && f.getName().equals("question")) || (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("id")) || (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("version")) || (f.getDeclaringClass() == QuestionColumnLabel.class && f.getName().equals("question")); return skip; } }); //de-proxy the object gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer()); Hibernate.initialize(surveyDefinition); if (surveyDefinition instanceof HibernateProxy) { surveyDefinition = (SurveyDefinition) ((HibernateProxy) surveyDefinition) .getHibernateLazyInitializer().getImplementation(); } Gson gson = gsonBuilder.serializeNulls().create(); return gson.toJson(surveyDefinition); } catch (Exception e) { log.error(e.getMessage(), e); throw (new RuntimeException(e)); } }
From source file:com.jd.survey.util.HibernateProxySerializer.java
License:Open Source License
@Override public JsonElement serialize(HibernateProxy proxyObj, Type arg1, JsonSerializationContext arg2) { try {/*from w w w . j a va 2s . com*/ GsonBuilder gsonBuilder = new GsonBuilder(); //below ensures deep deproxied serialization gsonBuilder.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxySerializer()); Object deProxied = proxyObj.getHibernateLazyInitializer().getImplementation(); return gsonBuilder.create().toJsonTree(deProxied); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:com.paysafe.common.impl.AddressContainerAdapter.java
License:Open Source License
/** * Instantiates a new address container adapter. *///w w w. j a v a2 s. c om public AddressContainerAdapter() { final GsonBuilder gsonSerializerBuilder = new GsonBuilder(); gsonSerializerBuilder.excludeFieldsWithoutExposeAnnotation(); gsonSerializerBuilder.registerTypeHierarchyAdapter(Id.class, new IdAdapter()); gsonSerializerBuilder.registerTypeHierarchyAdapter(Boolean.class, new BooleanAdapter()); gsonSerializer = gsonSerializerBuilder.create(); final GsonBuilder gsonDeserializerBuilder = new GsonBuilder(); gsonDeserializerBuilder.registerTypeHierarchyAdapter(Id.class, new IdAdapter()); gsonDeserializer = gsonDeserializerBuilder.create(); }
From source file:com.paysafe.PaysafeApiClient.java
License:Open Source License
/** * Instantiates a new paysafe API client. * * @param keyId the key id/* w w w . jav a 2s . c o m*/ * @param keyPassword the key password * @param environment the environment */ public PaysafeApiClient(final String keyId, final String keyPassword, final Environment environment) { this.keyId = keyId; this.keyPassword = keyPassword; this.environment = environment; apiEndPoint = this.environment.getUrl(); final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeHierarchyAdapter(AddressContainer.class, new AddressContainerAdapter()); gsonBuilder.registerTypeHierarchyAdapter(Boolean.class, new BooleanAdapter()); gsonBuilder.registerTypeHierarchyAdapter(Id.class, new IdAdapter()); gsonDeserializer = gsonBuilder.create(); }
From source file:com.paysafe.PaysafeApiClient.java
License:Open Source License
/** * Take a domain object, and json serialize it. * * @param request the request/*from w w w . jav a2 s .com*/ * @param returnType the return type * @return json encoding of the request object */ private String serializeObject(Request request, Class<?> returnType) { final GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.excludeFieldsWithoutExposeAnnotation(); gsonBuilder.registerTypeHierarchyAdapter(AddressContainer.class, new AddressContainerAdapter()); gsonBuilder.registerTypeHierarchyAdapter(Id.class, new IdAdapter()); if (null != request.getSerializer()) { gsonBuilder.registerTypeAdapter(returnType, request.getSerializer()); } final Gson gson = gsonBuilder.create(); return gson.toJson(request.getBody()); }
From source file:com.pmeade.arya.Arya.java
License:Open Source License
/** * Obtain the Google Gson singleton. If the singleton does not exist, * it will be created on the first call to this method. * @return Gson object, properly configured for JSON (de)serialization *//*ww w . j a v a 2s. co m*/ private Gson getGson() { // if we don't have a Gson singleton yet if (gson == null) { // create a builder object to generate a customized Gson object GsonBuilder gsonBuilder = new GsonBuilder(); // register Arya's serializer to handle serialization of every // object that derives from Object (i.e.: all objects) gsonBuilder.registerTypeHierarchyAdapter(Object.class, new AryaSerializer(this)); // register Arya's deserializer to handle deserialization of every // object that derives from Object (i.e.: all objects) gsonBuilder.registerTypeHierarchyAdapter(Object.class, new AryaDeserializer(this)); // if Arya was configured for pretty printing if (prettyPrinting) { // then, configure our Gson singleton for pretty printing gsonBuilder.setPrettyPrinting(); } // create the Gson singleton gson = gsonBuilder.create(); } // return the Gson singleton to the caller return gson; }
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
License:Open Source License
/** * <p>//from ww w. java2 s.c o m * Address Book Synchronization rest service post method which gets Json * string, which contains list of Address Book records. This method performs * save or update operations. It returns Json string with local address code * with IOS address code. * </p> * * @param jsonAddressBookListString * */ @POST @Path("/sync") @Consumes(MediaType.TEXT_PLAIN) @Produces({ MediaType.APPLICATION_JSON }) public Response syncAddressBook(String jsonAddressBookListString) { log.log(Level.INFO, "Address Book --> Sync Record "); log.log(Level.INFO, "Address Book --> Sync Record --> Data for Sync... ::::: " + jsonAddressBookListString); MsgBeans beans = new MsgBeans(); AuditTrailMaintenance auditTrailMaint = new AuditTrailMaintenance(); List<AddressBook> jsonObjList = new ArrayList(); GsonBuilder builder = new GsonBuilder(); AddressBookMaintenance addressBookMaintenance = new AddressBookMaintenance(); Gson googleJson = null; Type listType = null; String returnJsonString = ""; try { returnJsonString = "["; builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { @Override public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Date date = LMSUtil.convertDateToyyyymmddhhmmssDashed(json.getAsString()); if (null != date) { return date; } else { return LMSUtil.convertDateToyyyy_mm_dd(json.getAsString()); } } }); builder.registerTypeHierarchyAdapter(byte[].class, new JsonDeserializer<byte[]>() { public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return Base64.decodeBase64(json.getAsString()); } }); googleJson = builder.create(); listType = new TypeToken<List<AddressBook>>() { }.getType(); jsonObjList = googleJson.fromJson(jsonAddressBookListString, listType); // maintain in single transaction returnJsonString += addressBookMaintenance.insertOrUpdateRestBatch(jsonObjList); returnJsonString += "]"; log.log(Level.INFO, "Address Book --> saved successfully "); auditTrailMaint.insertAuditTrail( new AuditTrail("Rest", AuditTrail.MODULE_ADDRESS_BOOK, AuditTrail.FUNCTION_SUCCESS, "SUCCESS")); return Response.status(200).entity(returnJsonString).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 Save Record."); log.log(Level.SEVERE, e.getMessage()); e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); LogsMaintenance logsMain = new LogsMaintenance(); logsMain.insertLogs("AddressBookRest", Level.SEVERE + "", errors.toString()); return Response.status(200).entity(googleJson.toJson(beans)).build(); } finally { jsonObjList.clear(); auditTrailMaint = null; addressBookMaintenance = null; builder = null; googleJson = null; listType = null; returnJsonString = null; beans = null; System.gc(); } }
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
License:Open Source License
/** * <p>//from w ww . j a v a 2 s . co m * This method retrieves List of Address Book for particular Agent. * </p> * * @param agentId * */ @GET @Path("/getAgentAddressBook") @Produces(MediaType.APPLICATION_JSON) public Response getAgentAddressBook(@Context HttpServletRequest request, @Context ServletContext context) { log.log(Level.INFO, "Address Book --> getAgentAddressBook "); 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 ... "); addressBookList = addressBookMaintenance.getAgentAddressBook(request, context); // Convert the object to a JSON string log.log(Level.INFO, "Address Book --> Information fetched successfully... "); jsonString = googleJson.toJson(addressBookList); 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)); LogsMaintenance logsMain = new LogsMaintenance(); 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(); } }