List of usage examples for com.google.gson JsonSerializer JsonSerializer
JsonSerializer
From source file:com.mmj.app.common.util.CityUtils.java
License:Open Source License
private static Map<Integer, List<CityMeta>> parse(String json) { final Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() { @Override//from w w w . j ava 2 s .c om public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { Integer value = src.intValue(); return new JsonPrimitive(value); } }).create(); List<?> list = gson.fromJson(json, new TypeToken<Object>() { }.getType()); if (list == null || list.size() == 0) { return Collections.emptyMap(); } Map<Integer, List<CityMeta>> map = new HashMap<Integer, List<CityMeta>>(); for (Object obj : list) { if (obj == null) { continue; } if (obj instanceof Map<?, ?>) { Number parentId = (Number) ((Map<?, ?>) obj).get("id"); Integer pId = parentId.intValue(); List<?> data = (List<?>) ((Map<?, ?>) obj).get("data"); if (parentId == null || data == null) { continue; } List<CityMeta> cityList = new ArrayList<CityUtils.CityMeta>(); for (Object value : data) { if (value instanceof Map<?, ?>) { cityList.add(new CityMeta((Double) ((Map<?, ?>) value).get("id"), (String) ((Map<?, ?>) value).get("name"))); } } map.put(pId, cityList); } } return map; }
From source file:com.nuevebit.miroculus.mrna.rest.util.gson.MiRNAGsonConverter.java
private GsonBuilder configureBuilder(GsonBuilder builder) { builder.addDeserializationExclusionStrategy(exclusionStrat); builder.addSerializationExclusionStrategy(exclusionStrat); builder.registerTypeAdapter(Author.class, new JsonSerializer<Author>() { @Override//from ww w .j a va2 s . c o m public JsonElement serialize(Author src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.getName()); } }); return builder; }
From source file:com.onedrive.sdk.serializer.GsonFactory.java
License:Open Source License
/** * Creates an instance of Gson.// ww w. j a va 2 s. co m * @param logger The logger. * @return The new instance. */ public static Gson getGsonInstance(final ILogger logger) { final JsonSerializer<Calendar> dateJsonSerializer = new JsonSerializer<Calendar>() { @Override public JsonElement serialize(final Calendar src, final Type typeOfSrc, final JsonSerializationContext context) { if (src == null) { return null; } try { return new JsonPrimitive(CalendarSerializer.serialize(src)); } catch (final Exception e) { logger.logError("Parsing issue on " + src, e); return null; } } }; final JsonDeserializer<Calendar> dateJsonDeserializer = new JsonDeserializer<Calendar>() { @Override public Calendar deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json == null) { return null; } try { return CalendarSerializer.deserialize(json.getAsString()); } catch (final ParseException e) { logger.logError("Parsing issue on " + json.getAsString(), e); return null; } } }; return new GsonBuilder().registerTypeAdapter(Calendar.class, dateJsonSerializer) .registerTypeAdapter(Calendar.class, dateJsonDeserializer).create(); }
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
License:Open Source License
/** * <p>//from www .j av a 2 s .c o 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(); } }
From source file:com.quix.aia.cn.imo.rest.AddressBookRest.java
License:Open Source License
@GET @Path("/getCCTestResults") @Produces(MediaType.APPLICATION_JSON)/* w w w . j a va 2 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 w w. j av a 2s .c om*/ 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 . co 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.tmall.wireless.tangram.example.dataparser.SampleDataParser.java
License:Open Source License
private void addCardStyle(JSONObject cardData, Card card) { try {// ww w. j a v a2 s.c o m GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Float.class, new JsonSerializer<Float>() { @Override public JsonElement serialize(final Float src, final Type typeOfSrc, final JsonSerializationContext context) { try { if (src.isInfinite() || src.isNaN()) { return new JsonPrimitive(0f); } BigDecimal value = BigDecimal.valueOf(src); return new JsonPrimitive(value); } catch (Exception e) { e.printStackTrace(); } return new JsonPrimitive(0f); } }); Gson gson = gsonBuilder.create(); GridCard.GridStyle gridStyle = new GridCard.GridStyle(); if (card instanceof BannerCard) { gridStyle.aspectRatio = 3.223f; } cardData.put(Card.KEY_STYLE, new JSONObject(gson.toJson(gridStyle))); } catch (JSONException e) { e.printStackTrace(); } }
From source file:com.tsc9526.monalisa.tools.json.MelpJson.java
License:Open Source License
public static GsonBuilder createGsonBuilder() { return new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() { public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) { if (src == src.longValue()) { return new JsonPrimitive(src.longValue()); }//from w w w . j av a 2 s . co m return new JsonPrimitive(src); } }).setExclusionStrategies(new ExclusionStrategy() { public boolean shouldSkipField(FieldAttributes fa) { return fa.getName().startsWith("$"); } public boolean shouldSkipClass(Class<?> clazz) { return false; } }).setDateFormat(Conversion.DEFAULT_DATETIME_FORMAT); }
From source file:com.vimeo.networking.utils.ISO8601.java
License:Open Source License
public static JsonSerializer<Date> getDateSerializer() { return new JsonSerializer<Date>() { @Override/*from w w w. ja v a 2 s . c om*/ public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { return src == null ? null : new JsonPrimitive(fromDate(src)); } }; }