Example usage for com.google.gson JsonSerializer JsonSerializer

List of usage examples for com.google.gson JsonSerializer JsonSerializer

Introduction

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

Prototype

JsonSerializer

Source Link

Usage

From source file:br.edu.unochapeco.unoheartserver.util.CustomGsonBuilder.java

public static Gson getInstance() {
    if (gson == null) {

        gson = new GsonBuilder().registerTypeAdapter(LocalDate.class,
                (JsonSerializer<LocalDate>) new JsonSerializer<LocalDate>() {

                    @Override//from   w  w  w.ja  va 2 s. c o  m
                    public JsonElement serialize(LocalDate t, java.lang.reflect.Type type,
                            JsonSerializationContext jsc) {
                        if (t != null) {
                            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                            return new JsonPrimitive(t.format(dateTimeFormatter));
                        } else {
                            return null;
                        }
                    }
                }).registerTypeAdapter(LocalDate.class,
                        (JsonDeserializer<LocalDate>) new JsonDeserializer<LocalDate>() {

                            @Override
                            public LocalDate deserialize(JsonElement je, java.lang.reflect.Type type,
                                    JsonDeserializationContext jdc) {
                                if (je.getAsJsonPrimitive().getAsString() != null) {
                                    return LocalDate.parse(
                                            je.getAsJsonPrimitive().getAsString().substring(0, 10).trim(),
                                            DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                                } else {
                                    return null;
                                }
                            }
                        })
                .registerTypeAdapter(LocalDateTime.class,
                        (JsonSerializer<LocalDateTime>) new JsonSerializer<LocalDateTime>() {

                            @Override
                            public JsonElement serialize(LocalDateTime t, java.lang.reflect.Type type,
                                    JsonSerializationContext jsc) {
                                if (t != null) {
                                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter
                                            .ofPattern("yyyy-MM-dd'T'HH:mm:ss");
                                    return new JsonPrimitive(t.format(dateTimeFormatter));
                                } else {
                                    return null;
                                }
                            }
                        })
                .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (JsonElement je,
                        java.lang.reflect.Type type, JsonDeserializationContext jdc) -> {
                    if (je.getAsJsonPrimitive().getAsString() != null) {
                        return LocalDateTime.parse(je.getAsJsonPrimitive().getAsString().trim(),
                                DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
                    } else {
                        return null;
                    }
                }).create();
    }
    return gson;
}

From source file:br.ufmg.hc.telessaude.webservices.mobile.utils.GsonUtils.java

public static Gson getInstanceWithStringDateAdapter() {
    GsonBuilder builder = new GsonBuilder();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    //        final SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a");
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

        @Override//ww  w.j  a  v a  2s . c  o  m
        public Date deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            String data_str = "";
            Date data = null;
            try {
                data_str = je.getAsJsonPrimitive().getAsString();
                if (data_str.replaceAll("[\\-\\d]", "").isEmpty()) {
                    data = new Date(Long.parseLong(data_str));

                } else {
                    if (data_str.length() == 12) {
                        data = new SimpleDateFormat("MMM dd, yyyy").parse(data_str);
                    } else if (data_str.length() == 11) {
                        data = new SimpleDateFormat("MMM d, yyyy").parse(data_str);
                    } else if (data_str.length() == 10) {
                        data = new SimpleDateFormat("dd/MM/yyyy").parse(data_str);
                    } else {

                        data = sdf.parse(data_str);
                    }
                }
            } catch (ParseException ex) {
                Logger.getLogger(GsonUtils.class.getName()).log(Level.SEVERE, null, ex);
            }
            return data;
        }
    });
    builder.registerTypeAdapter(Date.class, new JsonSerializer<Date>() {
        @Override
        public JsonElement serialize(Date t, Type type, JsonSerializationContext jsc) {
            if (t == null) {
                return new JsonPrimitive((String) null);
            }
            return new JsonPrimitive(sdf.format(t));
        }
    });

    builder.registerTypeAdapter(java.sql.Date.class, new JsonSerializer<java.sql.Date>() {
        @Override
        public JsonElement serialize(java.sql.Date t, Type type, JsonSerializationContext jsc) {
            if (t == null) {
                return new JsonPrimitive((String) null);
            }
            return new JsonPrimitive(sdf.format(t));
        }
    });
    return builder.create();
}

From source file:cn.teamlab.wg.framework.struts2.json.JsonSerializerBuilder.java

License:Apache License

public static GsonBuilder builder() {
    return new GsonBuilder() //
            .disableHtmlEscaping().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override/* w  w w . ja  va  2  s  .  c o m*/
                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));
                }
            });
}

From source file:com.balajeetm.mystique.util.gson.GsonFactory.java

License:Open Source License

/**
 * Gets the gson builder./*  w  w  w. j a v a  2  s .c o m*/
 *
 * @return the gson builder
 */
public GsonBuilder getGsonBuilder() {
    if (null == gsonBuilder) {
        gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat(DateFormat.LONG, DateFormat.LONG);
        gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

            @Override
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                Date date = null;
                if (null != json && json.isJsonPrimitive()) {
                    date = new Date(json.getAsJsonPrimitive().getAsLong());
                }
                return date;
            }
        });
        gsonBuilder.registerTypeAdapter(XMLGregorianCalendar.class, new JsonSerializer<XMLGregorianCalendar>() {

            @Override
            public JsonElement serialize(XMLGregorianCalendar src, Type typeOfSrc,
                    JsonSerializationContext context) {
                Date date = null;
                if (null != src) {
                    date = src.toGregorianCalendar().getTime();
                }
                return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").format(date));
            }
        });
    }
    return gsonBuilder;
}

From source file:com.cloudant.client.org.lightcouch.internal.GsonHelper.java

License:Open Source License

/**
 * Builds {@link Gson} and registers any required serializer/deserializer.
 *
 * @return {@link Gson} instance/*from  w w  w .ja  va 2  s. c  o m*/
 */
public static GsonBuilder initGson(GsonBuilder gsonBuilder) {
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonDeserializer<JsonObject>() {
        public JsonObject deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return json.getAsJsonObject();
        }
    });
    gsonBuilder.registerTypeAdapter(JsonObject.class, new JsonSerializer<JsonObject>() {
        public JsonElement serialize(JsonObject src, Type typeOfSrc, JsonSerializationContext context) {
            return src.getAsJsonObject();
        }

    });

    return gsonBuilder;
}

From source file:com.code19.library.GsonUtil.java

License:Apache License

public static String objectToJsonDateSerializer(Object ts, final String dateformat) {
    String jsonStr = null;/*from  ww w.  j  ava 2  s. com*/
    gson = new GsonBuilder().registerTypeHierarchyAdapter(Date.class, new JsonSerializer<Date>() {
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            SimpleDateFormat format = new SimpleDateFormat(dateformat);
            return new JsonPrimitive(format.format(src));
        }
    }).setDateFormat(dateformat).create();
    if (gson != null) {
        jsonStr = gson.toJson(ts);
    }
    return jsonStr;
}

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. //  www . j  a  v  a 2  s.  c  o 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.gwtjsonrpc.server.JsonServlet.java

License:Apache License

private String formatResult(final ActiveCall call) throws UnsupportedEncodingException, IOException {
    final GsonBuilder gb = createGsonBuilder();
    gb.registerTypeAdapter(call.getClass(), new JsonSerializer<ActiveCall>() {
        public JsonElement serialize(final ActiveCall src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (call.callback != null) {
                if (src.externalFailure != null) {
                    return new JsonNull();
                }//w ww.  j  a  v  a2s .  com
                return context.serialize(src.result);
            }

            final JsonObject r = new JsonObject();
            r.add(src.versionName, src.versionValue);
            if (src.id != null) {
                r.add("id", src.id);
            }
            if (src.xsrfKeyOut != null) {
                r.addProperty("xsrfKey", src.xsrfKeyOut);
            }
            if (src.externalFailure != null) {
                final JsonObject error = new JsonObject();
                if ("jsonrpc".equals(src.versionName)) {
                    final int code = to2_0ErrorCode(src);

                    error.addProperty("code", code);
                    error.addProperty("message", src.externalFailure.getMessage());
                } else {
                    error.addProperty("name", "JSONRPCError");
                    error.addProperty("code", 999);
                    error.addProperty("message", src.externalFailure.getMessage());
                }
                r.add("error", error);
            } else {
                r.add("result", context.serialize(src.result));
            }
            return r;
        }
    });

    final StringWriter o = new StringWriter();
    if (call.callback != null) {
        o.write(call.callback);
        o.write("(");
    }
    gb.create().toJson(call, o);
    if (call.callback != null) {
        o.write(");");
    }
    o.close();
    return o.toString();
}

From source file:com.jiandanbaoxian.ui.buyinsurance.car_insurance.CarInsurancePricePlanActivity.java

/**
 * /*w w  w.  jav  a  2s  .c o  m*/
 */
private void toQuotaPrice() {
    tvQuotaPrice.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int uid = PreferenceUtil.load(activity, PreferenceConstant.userid, -1);

            if (uid < 0) {
                Toast.makeText(activity, "???", Toast.LENGTH_SHORT).show();
                LoginActivity.startLoginActivity(activity);
                return;
            }
            userid = uid + "";

            if (TextUtils.isEmpty(transfer)) {
                transfer = "0";
            }
            if (TextUtils.isEmpty(transferDate)) {
                transferDate = "0";
            }

            insuranceItemDatas.clear();
            //?
            if (flag_switch_SDEWMotorVehicleLossInsurance) {
                insuranceItemDatas.add(motor_vehicle_loss_insurance);
            }
            //?
            if (flag_switch_SDEWCabSeatInsurance) {
                insuranceItemDatas.add(cab_seat_insurance);
            }
            //
            if (flag_switch_SDEWPassengerSeatInsurance) {
                insuranceItemDatas.add(passenger_seat_insurance);
            }
            //
            if (flag_switch_SDEWRiskOfSpontaneousCombustionInsurance) {
                insuranceItemDatas.add(risk_of_spontaneous_combustion_insurance);
            }
            //?
            if (flag_switch_SDEWRiskOfEngineWadingInsurance) {
                insuranceItemDatas.add(risk_of_engine_wading_insurance);
            }
            //
            if (flag_switch_SDEWRiskOfScratchesInsurance) {
                insuranceItemDatas.add(risk_of_scratches_insurance);
            }
            //
            if (flag_switch_SDEWRobInsurance) {
                insuranceItemDatas.add(rob_insurance);
            }
            //
            if (flag_switch_SDEWShadeLiningInsurance) {
                insuranceItemDatas.add(shade_lining_insurance);
            }
            //
            if (flag_switch_SDEWThirdResponsibilityInsurance) {
                insuranceItemDatas.add(third_responsibility_insurance);

            }

            Gson gson = new GsonBuilder().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.doubleValue())
                        return new JsonPrimitive(nf.format(src.doubleValue()));
                    else if (src == src.longValue())
                        return new JsonPrimitive(nf.format(src.longValue()));
                    return new JsonPrimitive(nf.format(src));
                }
            }).create();

            insuranceItems = gson.toJson(insuranceItemDatas);
            progressDialogUtil.show("???...");
            //2
            UserRetrofitUtil.quotaPrice(activity, userid, licenseplate, engineNumber, frameNumber,
                    seatingcapacity, newValue + "", model_code, registrationDateString, ownerName,
                    commercestartdate + "", compulsorystartdate + "", issueDateString, provence, provnce_no,
                    city_no, country_no, transfer, transferDate, idcardNum, phone, compulsoryAmt,
                    insuranceItems, type, glassType, new NetCallback<NetWorkResultBean<Object>>(activity) {
                        @Override
                        public void onFailure(RetrofitError error, String message) {

                            progressDialogUtil.hide();
                            Toast.makeText(activity, "", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void success(NetWorkResultBean<Object> commPriceDataNetWorkResultBean,
                                Response response) {
                            progressDialogUtil.hide();

                            if (commPriceDataNetWorkResultBean != null) {
                                int status = commPriceDataNetWorkResultBean.getStatus();
                                switch (status) {
                                case HttpsURLConnection.HTTP_OK:
                                    if (commPriceDataNetWorkResultBean.getData() != null) {

                                        CommPriceData bean = null;
                                        Object obj = commPriceDataNetWorkResultBean.getData();
                                        if (obj instanceof String) {
                                            Toast.makeText(activity,
                                                    commPriceDataNetWorkResultBean.getMessage().toString(),
                                                    Toast.LENGTH_LONG).show();
                                            return;
                                        }
                                        try {
                                            String json = com.jiandanbaoxian.util.JsonUtil.toJson(obj);
                                            bean = com.jiandanbaoxian.util.JsonUtil.fromJson(json,
                                                    CommPriceData.class);
                                        } catch (Exception e) {
                                            Log.e("qw", "???!");
                                        }
                                        if (bean == null) {
                                            Toast.makeText(activity, "?", Toast.LENGTH_LONG)
                                                    .show();
                                            return;
                                        }

                                        PriceReportActivity.startActivity(activity, bean, idcardNum, city_no,
                                                country_no, provnce_no, compulsorystartdate, commercestartdate);
                                    }
                                    break;
                                default:
                                    Toast.makeText(activity,
                                            commPriceDataNetWorkResultBean.getMessage().toString(),
                                            Toast.LENGTH_LONG).show();
                                    break;
                                }
                            }

                        }
                    });
        }
    });
}

From source file:com.microsoft.graph.serializer.GsonFactory.java

License:Open Source License

/**
 * Creates an instance of Gson./*from   w w w. ja  v  a 2  s .co m*/
 *
 * @param logger The logger.
 * @return The new instance.
 */
public static Gson getGsonInstance(final ILogger logger) {

    final JsonSerializer<Calendar> calendarJsonSerializer = 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> calendarJsonDeserializer = 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;
            }
        }
    };

    final JsonSerializer<byte[]> byteArrayJsonSerializer = new JsonSerializer<byte[]>() {
        @Override
        public JsonElement serialize(final byte[] src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            try {
                return new JsonPrimitive(ByteArraySerializer.serialize(src));
            } catch (final Exception e) {
                logger.logError("Parsing issue on " + src, e);
                return null;
            }
        }
    };

    final JsonDeserializer<byte[]> byteArrayJsonDeserializer = new JsonDeserializer<byte[]>() {
        @Override
        public byte[] deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            if (json == null) {
                return null;
            }
            try {
                return ByteArraySerializer.deserialize(json.getAsString());
            } catch (final ParseException e) {
                logger.logError("Parsing issue on " + json.getAsString(), e);
                return null;
            }
        }
    };

    final JsonSerializer<DateOnly> dateJsonSerializer = new JsonSerializer<DateOnly>() {
        @Override
        public JsonElement serialize(final DateOnly src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            return new JsonPrimitive(src.toString());
        }
    };

    final JsonDeserializer<DateOnly> dateJsonDeserializer = new JsonDeserializer<DateOnly>() {
        @Override
        public DateOnly deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            if (json == null) {
                return null;
            }

            try {
                return DateOnly.parse(json.getAsString());
            } catch (final ParseException e) {
                logger.logError("Parsing issue on " + json.getAsString(), e);
                return null;
            }
        }
    };

    return new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
            .registerTypeAdapter(Calendar.class, calendarJsonSerializer)
            .registerTypeAdapter(Calendar.class, calendarJsonDeserializer)
            .registerTypeAdapter(GregorianCalendar.class, calendarJsonSerializer)
            .registerTypeAdapter(GregorianCalendar.class, calendarJsonDeserializer)
            .registerTypeAdapter(byte[].class, byteArrayJsonDeserializer)
            .registerTypeAdapter(byte[].class, byteArrayJsonSerializer)
            .registerTypeAdapter(DateOnly.class, dateJsonSerializer)
            .registerTypeAdapter(DateOnly.class, dateJsonDeserializer)
            .registerTypeAdapterFactory(new FallBackEnumTypeAdapter()).create();
}