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:com.webservice.MovieService.java

public Movie fromJSON(String string) {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // UTC
    Gson gson = gsonBuilder.create();//  w w w . ja v  a2  s . c o  m

    return gson.fromJson(string, Movie.class);

}

From source file:de.dentrassi.pm.npm.ModuleHandler.java

License:Open Source License

public void process(final OutputStream stream) throws IOException {
    final String sitePrefix = this.service.getDefaultSitePrefix();

    final GsonBuilder builder = new GsonBuilder();
    if (this.pretty) {
        builder.setPrettyPrinting();/*from  w ww . j ava 2s .  c o m*/
    }

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

    final Gson gson = builder.create();

    final JsonParser parser = new JsonParser();

    final TreeMap<String, PackageEntry> versions = new TreeMap<>();

    for (final Artifact art : this.channel.getArtifacts()) {
        final String pkg = art.getInformation().getMetaData()
                .get(new MetaKey(NpmChannelAspectFactory.ID, "package.json"));
        if (pkg == null) {
            continue;
        }

        try {
            final JsonElement pkgEle = parser.parse(pkg);
            final PackageInfo pi = gson.fromJson(pkgEle, PackageInfo.class);

            if (!this.moduleName.equals(pi.getName())) {
                continue;
            }

            versions.put(pi.getVersion(), new PackageEntry(pi, pkgEle, art));
        } catch (final Exception e) {
            logger.info("Failed to parse package.json of " + art.getId(), e);
            continue;
        }
    }

    // now build the main file

    final JsonObject main = new JsonObject();

    // pull in meta data from most recent version

    main.addProperty("name", this.moduleName);

    if (!versions.isEmpty()) {
        final Entry<String, PackageEntry> mostRecent = versions.lastEntry();
        final PackageInfo pi = mostRecent.getValue().getInfo();
        main.addProperty("license", pi.getLicense());

        final JsonObject distTags = new JsonObject();
        main.add("dist-tags", distTags);

        distTags.addProperty("latest", pi.getVersion());
    }

    final JsonObject times = new JsonObject();
    main.add("time", times);

    final JsonObject versionsEle = new JsonObject();
    main.add("versions", versionsEle);

    for (final Map.Entry<String, PackageEntry> entry : versions.entrySet()) {
        final PackageInfo pi = entry.getValue().getInfo();
        final Artifact art = entry.getValue().getArtifact();

        times.add(pi.getVersion(), gson.toJsonTree(art.getInformation().getCreationTimestamp()));

        final JsonObject ele = (JsonObject) entry.getValue().getElement();

        final JsonObject dist = new JsonObject();
        dist.addProperty("shasum", art.getInformation().getMetaData().get(new MetaKey("hasher", "sha1")));
        dist.addProperty("tarball", String.format("%s/artifact/%s/dump", sitePrefix, art.getId()));

        ele.add("dist", dist);

        versionsEle.add(pi.getVersion(), ele);
    }

    // render

    try (OutputStreamWriter out = new OutputStreamWriter(stream, StandardCharsets.UTF_8)) {
        gson.toJson(main, out);
    }
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

public static Gson createDataGson() {
    GsonBuilder gson = new GsonBuilder();
    gson.setDateFormat("yyyy-MM-dd");
    return gson.disableHtmlEscaping().create();
    //return gson.disableHtmlEscaping().setPrettyPrinting().create();
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

public static Gson createComponentJson() {
    GsonBuilder gson = new GsonBuilder();
    gson.setDateFormat("yyyy-MM-dd");
    return gson.disableHtmlEscaping().create();
    //return gson.disableHtmlEscaping().setPrettyPrinting().create();
}

From source file:edu.isi.wings.portal.classes.JsonHandler.java

License:Apache License

public static Gson createTemplateGson() {
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Link.class, new LinkSerializer());
    //gson.registerTypeAdapter(Node.class, new NodeSerializer());
    gson.registerTypeAdapter(Binding.class, new BindingSerializer());
    gson.registerTypeAdapter(Binding.class, new BindingDeserializer());
    gson.registerTypeAdapter(ValueBinding.class, new BindingSerializer());
    gson.registerTypeAdapter(ValueBinding.class, new BindingDeserializer());
    gson.registerTypeAdapter(SetExpression.class, new SetExpressionSerializer());
    gson.registerTypeAdapter(SetExpression.class, new SetExpressionDeserializer());
    //gson.registerTypeAdapter(URI.class, new URISerializer());
    //gson.registerTypeAdapter(String.class, new StringSerializer());
    gson.setDateFormat("yyyy-MM-dd");
    gson.disableHtmlEscaping();//from  w w w.  j  av  a2  s.  co  m
    //gson.setPrettyPrinting();
    return gson.create();
}

From source file:edu.mayo.cts2.framework.core.json.JsonConverter.java

License:Open Source License

/**
 * Builds the gson./*from w  w w .  j ava  2 s. com*/
 *
 * @return the gson
 */
protected Gson buildGson() {
    GsonBuilder gson = new GsonBuilder();

    gson.setDateFormat(ISO_DATE_FORMAT);

    gson.setExclusionStrategies(new ExclusionStrategy() {

        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getName().equals(CHOICE_VALUE);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }

    });

    gson.registerTypeAdapter(List.class, new EmptyCollectionSerializer());
    gson.registerTypeAdapter(TsAnyType.class, new TsAnyTypeSerializer());
    gson.registerTypeAdapter(Date.class, new DateTypeAdapter());
    gson.registerTypeAdapterFactory(new ChangeableTypeAdapterFactory());
    gson.registerTypeAdapterFactory(new ChangeableResourceTypeAdapterFactory());

    gson.setFieldNamingStrategy(new FieldNamingStrategy() {

        @Override
        public String translateName(Field field) {
            String fieldName = field.getName();

            char[] array = fieldName.toCharArray();

            if (array[0] == '_') {
                array = ArrayUtils.remove(array, 0);
            }

            String name = new String(array);
            if (name.endsWith(LIST_SUFFIX)) {
                name = StringUtils.removeEnd(name, LIST_SUFFIX);
            }

            return name;
        }

    });

    return gson.create();
}

From source file:ee.ria.dumonitor.common.util.GsonFactory.java

License:Open Source License

/**
 * @return a new Gson instance with the required configuration for this application.
 *//*  w  ww.  j  a v a  2 s. co  m*/
public static Gson createGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(DateUtil.ISO_8601_FORMAT);
    return builder.create();
}

From source file:es.alrocar.poiproxy.fiware.poidp.schema.POISet.java

License:Apache License

protected Gson gson() {
    if (gson == null) {
        GsonBuilder lObjJson = new GsonBuilder();
        lObjJson.setDateFormat("yyyy/MM/dd HH:mm:ss");
        lObjJson.registerTypeAdapter(Date.class, new DateTypeAdapter());
        lObjJson.setPrettyPrinting();/*from w w  w. j av a2s . com*/
        gson = lObjJson.create();
    }
    return gson;
}

From source file:eu.gloriaproject.tools.reservationlist.ReservationListController.java

License:Open Source License

@ResourceMapping(value = "getSlots")
public void getSlots(ResourceRequest request, ResourceResponse response) throws IOException {

    String telescope = request.getParameter("telescopeSelectedName");

    System.out.println("Telescopio: " + telescope);

    ResourceBundle rb = ResourceBundle.getBundle("Language", request.getLocale());

    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
    String emailUser = themeDisplay.getUser().getEmailAddress();
    String passwordUser = themeDisplay.getUser().getPassword();

    // Get the list of slots from the Service
    List<Slot> timeSlots;/*  w w  w  . j a  va2 s. c  om*/
    try {
        // TODO To set as an argument telescope and experiment
        timeSlots = reservationsService.getReservationsList(emailUser, passwordUser);

        Map<String, Object> results = new HashMap<String, Object>();
        results.put("slots", timeSlots);
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd HH:mm:ss");
        String json = gsonBuilder.create().toJson(results);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Writer writer = response.getWriter();
        writer.write(json);
    } catch (OnlineExperimentException e) {
        log.error(e.getMessage());
        log.error("There is no timeslots available");
        log.error(e.getMessage());
        Map<String, Object> results = new HashMap<String, Object>();
        results.put("success", "false");
        results.put("message", rb.getString("msg-error-not-slots"));
        String json = new Gson().toJson(results);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        Writer writer = response.getWriter();
        writer.write(json);
    } catch (ExperimentReservationArgumentException e) {
        log.error(e.getMessage());
    } catch (ConnectionException e) {
        log.error(e.getMessage());
    } catch (ExperimentOperationException e) {
        log.error(e.getMessage());
    } catch (NoSuchOperationException e) {
        log.error(e.getMessage());
    } catch (ExperimentParameterException e) {
        log.error(e.getMessage());
    } catch (ExperimentNotInstantiatedException e) {
        log.error(e.getMessage());
    } catch (NoSuchReservationException e) {
        log.error(e.getMessage());
    } catch (NoSuchExperimentException e) {
        log.error(e.getMessage());
    }

}

From source file:fr.dudie.keolis.client.KeoUtils.java

License:Open Source License

/**
 * Gets a gson instance dedicated to Keolis API.
 * //from  w w  w.j  a  va 2 s.c  om
 * @return the gson instance
 */
public static Gson getGsonInstance() {

    if (gsonInstance == null) {
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss");

        // type adapter needed just because "data" object in the response can be an array or an
        // empty string.
        final Type lineAlertDataType = new TypeToken<LineAlertData>() {
        }.getType();
        gsonBuilder.registerTypeAdapter(lineAlertDataType, new LineAlertDataDeserializer());

        final Type listOfSubwayStation = new TypeToken<List<SubwayStation>>() {
        }.getType();
        gsonBuilder.registerTypeAdapter(listOfSubwayStation, new SubwayStationDeserializer());

        final Type listOfBikeStation = new TypeToken<List<BikeStation>>() {
        }.getType();

        gsonBuilder.registerTypeAdapter(listOfBikeStation, new BikeStationDeserializer());

        gsonInstance = gsonBuilder.create();
    }

    return gsonInstance;
}