Example usage for com.google.gson GsonBuilder setDateFormat

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

Introduction

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

Prototype

public GsonBuilder setDateFormat(int style) 

Source Link

Document

Configures Gson to to serialize Date objects according to the style value provided.

Usage

From source file:io.motown.operatorapi.json.gson.GsonFactoryBean.java

License:Apache License

public Gson createGson() {
    GsonBuilder builder = new GsonBuilder();

    if (dateFormat != null && !dateFormat.isEmpty()) {
        builder.setDateFormat(dateFormat);
    }// w  w  w  .ja  v a  2 s  .c o m

    for (TypeAdapterDeserializer<?> typeAdapterDeserializer : typeAdapterDeserializers) {
        builder.registerTypeAdapter(typeAdapterDeserializer.getAdaptedType(), typeAdapterDeserializer);
    }

    for (TypeAdapterSerializer<?> typeAdapterSerializer : typeAdapterSerializers) {
        builder.registerTypeAdapter(typeAdapterSerializer.getAdaptedType(), typeAdapterSerializer);
    }

    return builder.create();
}

From source file:io.urbanthings.api.transit.TransitApiManager.java

License:Apache License

protected final static Gson getGson() {
    if (gson == null) {
        GsonBuilder builder = new GsonBuilder();

        builder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        RuntimeTypeAdapterFactory<JourneyLeg> journeyLegAdapterFactory = RuntimeTypeAdapterFactory
                .of(JourneyLeg.class, "type");
        journeyLegAdapterFactory.registerSubtype(TransitJourneyLeg.class, "TransitJourneyLeg");
        builder.registerTypeAdapterFactory(journeyLegAdapterFactory);

        RuntimeTypeAdapterFactory<PlacePoint> placePointAdapterFactory = RuntimeTypeAdapterFactory
                .of(PlacePoint.class, "subClassType");
        placePointAdapterFactory.registerSubtype(TransitStop.class, "TransitStop");
        builder.registerTypeAdapterFactory(placePointAdapterFactory);

        RuntimeTypeAdapterFactory<StopCall> stopCallAdapterFactory = RuntimeTypeAdapterFactory
                .of(StopCall.class, "subClassType");
        stopCallAdapterFactory.registerSubtype(MonitoredStopCall.class, "MonitoredStopCall");
        builder.registerTypeAdapterFactory(stopCallAdapterFactory);

        gson = builder.create();// w w  w .j  a  va  2  s  .  c  om
    }
    return gson;
}

From source file:io.weba.processor.flink.event.gson.factory.EventFactory.java

License:Open Source License

public Gson create() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Id.class, new IdSerializer());
    gsonBuilder.registerTypeAdapter(Type.class, new TypeSerializer());
    gsonBuilder.registerTypeAdapter(Visitor.class, new VisitorSerializer());
    gsonBuilder.registerTypeAdapter(Session.class, new SessionSerializer());
    gsonBuilder.registerTypeAdapter(Map.class, new MapSerializer());
    gsonBuilder.registerTypeAdapter(Payload.class, new MapSerializer());
    gsonBuilder.serializeNulls();//from  ww  w .ja  v  a 2s . c o  m
    gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING);
    gsonBuilder.enableComplexMapKeySerialization();

    return gsonBuilder.create();
}

From source file:it.marcoberri.mbmeteo.action.Get.java

License:Apache License

/**
 * Processes requests for both HTTP//  www.  j  a  va 2s  .co m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final PrintWriter out = response.getWriter();
    try {
        final Map params = request.getParameterMap();

        int limit = 25;

        if (params.containsKey("limit")) {
            final String s[] = (String[]) params.get("limit");
            limit = Integer.parseInt(s[0]);
        }

        int start = 0;
        if (params.containsKey("start")) {
            final String s[] = (String[]) params.get("start");
            start = Integer.parseInt(s[0]);
        }

        String order = "-time";
        if (params.containsKey("order")) {
            final String s[] = (String[]) params.get("order");
            order = s[0];
        }

        final Datastore ds = MongoConnectionHelper.ds;
        final List<Meteolog> meteoLogList = ds.find(Meteolog.class).order(order).offset(start).limit(limit)
                .asList();
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyyMMddHHmm");
        final Gson gson = gsonBuilder.create();
        final HashMap endMap = new HashMap();
        endMap.put("data", meteoLogList);
        endMap.put("totalCount", ds.find(Meteolog.class).countAll());

        response.setContentType("application/json");
        response.setHeader("Content-Disposition", "attachment; filename=\"result.json\"");

        out.println(gson.toJson(endMap));
    } finally {
        out.close();
    }
}

From source file:it.marcoberri.mbmeteo.action.GetDistinctTime.java

License:Apache License

/**
 * Processes requests for both HTTP// www. j  a  v  a2s.c o  m
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    log.debug("start : " + this.getClass().getName());

    final PrintWriter out = response.getWriter();

    try {
        final Datastore ds = MongoConnectionHelper.ds;
        final List<Date> datesResult = ds.getDB().getCollection("Meteolog").distinct("time");
        final TreeMap<String, Date> dates = new TreeMap<String, Date>();

        final DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

        for (Date d : datesResult) {
            try {
                dates.put(df.format(d), d);
            } catch (Exception e) {
                log.error("error on data : " + d, e);
                continue;
            }
        }
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("dd-MM-yyyy");
        final Gson gson = gsonBuilder.create();

        response.setContentType("application/json");
        response.setHeader("Content-Disposition", "attachment; filename=\"result.json\"");
        out.println(gson.toJson(dates));

    } finally {
        out.close();
    }
}

From source file:k0n9.common.plugins.stripes.action.JsonBuilder.java

License:Apache License

@Override
public void build(Writer writer) throws Exception {
    GsonBuilder builder = new GsonBuilder().setExclusionStrategies(new JsonExclusionStrategy());
    builder.setDateFormat("yyyy-MM-dd HH:mm:ss");
    Gson gson = builder.create();//from   w  w w.ja va  2 s.  c  o  m
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonElement = jsonParser.parse(gson.toJson(getRootObject()));
    JsonWriter jsonWriter = gson.newJsonWriter(writer);
    gson.toJson(jsonElement, jsonWriter);
    jsonWriter.flush();
    jsonWriter.close();
}

From source file:net.daw.helper.statics.AppConfigurationHelper.java

License:MIT License

public static Gson getGson() throws Exception {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("dd/MM/yyyy");
    Gson oGson = gsonBuilder.excludeFieldsWithoutExposeAnnotation().create();
    return oGson;
}

From source file:net.daw.operaciones.BacklogGet.java

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String data;/*  ww  w.  j a va  2 s  . co m*/
    try {
        if (request.getParameter("id") == null) {
            data = "{\"error\":\"id is mandatory\"}";
        } else {
            BacklogDao oBacklogDAO = new BacklogDao(Conexion.getConection());
            BacklogBean oBacklog = new BacklogBean();
            oBacklog.setId(Integer.parseInt(request.getParameter("id")));
            oBacklogDAO.get(oBacklog);
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setDateFormat("dd/MM/yyyy");
            Gson gson = gsonBuilder.create();
            data = gson.toJson(oBacklog);

        }
        return data;
    } catch (Exception e) {
        throw new ServletException("BacklogGetJson: View Error: " + e.getMessage());
    }
}

From source file:net.daw.operaciones.CuestionarioGetcolumns.java

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ArrayList<String> alColumns = null;
    try {//from   w  w w. j a  va  2s  .c  o m
        CuestionarioDao oCuestionarioDAO = new CuestionarioDao(Conexion.getConection());
        alColumns = oCuestionarioDAO.getColumnsNames();
        String data;

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("dd/MM/yyyy");
        Gson gson = gsonBuilder.create();
        data = gson.toJson(alColumns);
        data = "{\"data\":" + data + "}";

        return data;
    } catch (Exception e) {
        throw new ServletException("CuestionarioGetcolumnsJson: View Error: " + e.getMessage());
    }
}

From source file:net.daw.operaciones.PacienteGet.java

@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String data;//from ww w . j  a  va2  s. c  o m
    try {
        if (request.getParameter("id") == null) {
            data = "{\"error\":\"id is mandatory\"}";
        } else {
            PacienteDao dao = new PacienteDao(Conexion.getConection(), "pacientes");
            PacienteBean bean = new PacienteBean();
            bean.setId(Integer.parseInt(request.getParameter("id")));
            dao.get(bean);
            GsonBuilder gsonBuilder = new GsonBuilder();
            gsonBuilder.setDateFormat("dd/MM/yyyy");
            Gson gson = gsonBuilder.create();
            data = gson.toJson(bean);
        }
        return data;
    } catch (Exception e) {
        throw new ServletException("PacienteGetJson: View Error: " + e.getMessage());
    }
}