Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:br.com.davimonteiro.lotus_runtime.config.ConfigurationUtil.java

License:Open Source License

public static Configuration save(Path configPath, Configuration config) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.setPrettyPrinting().create();

    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(gson.toJson(config));

    String json = gson.toJson(jsonElement);

    try {//from   w w  w  .  j a  v a 2  s  . c o m
        Files.write(configPath, json.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return config;
}

From source file:br.com.eventick.api.EventickAPI.java

License:Open Source License

public EventickAPI(String token) {
    this.gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssX").create();
    this.requests = new Requests();
    this.token = token;
}

From source file:br.com.financemate.bean.wsCep.ServicoEndereco.java

public EnderecoBean buscarEnderecoPor(String urlJson) {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    final Gson gson = gsonBuilder.create();
    EnderecoBean retornoEndereco = gson.fromJson(urlJson, EnderecoBean.class);
    return retornoEndereco;
}

From source file:br.com.gdgtresrios.sicomerciows.resource.GsonMessageBodyHandler.java

private Gson getGson() {
    if (gson == null) {
        final GsonBuilder gsonBuilder = new GsonBuilder();
        gson = gsonBuilder.create();//from  w  ww  . jav a2  s.c  o m
    }
    return gson;
}

From source file:br.com.infocarwebservice.rest.GsonMessageBodyHandler.java

License:Open Source License

private Gson getGson() {
    if (gson == null) {
        gson = new GsonBuilder().setPrettyPrinting().create();
    }
    return gson;
}

From source file:br.com.jsonxobj.main.UtilsJson.java

License:Apache License

/**
 * @param o --> object to json/*  w w  w. jav a 2 s .  c  o m*/
 * @return String with json
 */
public static String objToJson(Object o) {
    Gson gson = new GsonBuilder().create();
    String json = gson.toJson(o);
    String jsonWithNameObj = o.getClass().getName() + ";" + json; // ";"  to split the name of the object

    return jsonWithNameObj;
}

From source file:br.com.jsonxobj.main.UtilsJson.java

License:Apache License

/**
 * @param pathOfClass/*from  w  ww .  ja va  2s.c o  m*/
 * @param json
 * @return An object from json
 */
public static Object jsonToObj(String pathOfClass, String json) {
    Gson gson = new GsonBuilder().create();
    @SuppressWarnings("rawtypes")
    Class clazz = null;

    try {
        clazz = Class.forName(pathOfClass);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    @SuppressWarnings("unchecked")
    Object o = gson.fromJson(json, clazz);
    return o;
}

From source file:br.com.rsicarelli.supportlibraryexample.data.WonderPlacesServiceApiImpl.java

License:Apache License

@Override
public void getCachedWonderPlaces(final WonderPlacesServiceCallback<WonderPlaces> callback) {
    AsyncTask<Void, Void, WonderPlaces> asyncTask = new AsyncTask<Void, Void, WonderPlaces>() {
        @Override/*from  w w  w. j  a v a2s  . c o m*/
        protected WonderPlaces doInBackground(Void... params) {
            InputStream inputStream = ExampleApplication.getExampleApplication().getResources()
                    .openRawResource(R.raw.places);
            final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            Gson gson = new GsonBuilder()
                    .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC)
                    .serializeNulls().create();

            return gson.fromJson(reader, WonderPlaces.class);
        }

        @Override
        protected void onPostExecute(WonderPlaces places) {
            callback.onLoaded(places);
        }
    };
    asyncTask.execute();
}

From source file:br.com.saude.api.social.gcm.GcmServer.java

License:Open Source License

public GcmServer(String apiKey, String senderId, String serviceName) {
    jsonParser = new JsonParser();
    gson = new GsonBuilder().create();
    String username = senderId + "@" + Constants.GCM_HOST;
    smackCcsClient = new SmackCcsClient(apiKey, username, serviceName, Constants.GCM_HOST,
            Constants.GCM_CCS_PORT);//from w  ww.ja v a 2s.  com
    System.out.println("smackCcsClient(" + apiKey + ", " + username + ", " + serviceName + ", "
            + Constants.GCM_HOST + ", " + Constants.GCM_CCS_PORT + ")\n");

    // Add the GcmPacketExtension as an extension provider.
    ProviderManager.addExtensionProvider(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE,
            new ExtensionElementProvider<GcmPacketExtension>() {
                @Override
                public GcmPacketExtension parse(XmlPullParser parser, int initialDepth)
                        throws XmlPullParserException, IOException, SmackException {
                    String json = parser.nextText();
                    return new GcmPacketExtension(json);
                }
            });

    stanzaFilter = new StanzaFilter() {
        @Override
        public boolean accept(Stanza stanza) {
            // Accept messages from GCM CCS.
            if (stanza.hasExtension(Constants.GCM_ELEMENT_NAME, Constants.GCM_NAMESPACE)) {
                return true;
            }
            // Reject messages that are not from GCM CCS.
            return false;
        }
    };

    stanzaListener = new StanzaListener() {
        @Override
        public synchronized void processPacket(Stanza packet) throws SmackException.NotConnectedException {
            // Extract the GCM message from the packet.
            GcmPacketExtension packetExtension = (GcmPacketExtension) packet
                    .getExtension(Constants.GCM_NAMESPACE);

            JsonObject jGcmMessage = jsonParser.parse(packetExtension.getJson()).getAsJsonObject();
            String from = jGcmMessage.get("from").getAsString();

            // If there is no message_type normal GCM message is assumed.
            if (!jGcmMessage.has("message_type")) {
                if (StringUtils.isNotEmpty(from)) {
                    JsonObject jData = jGcmMessage.get("data").getAsJsonObject();
                    onMessage(from, jData);

                    // Send Ack to CCS to confirm receipt of upstream message.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    if (StringUtils.isNotEmpty(messageId)) {
                        sendAck(from, messageId);
                    } else {
                        logger.log(Level.SEVERE, "Message ID is null or empty.");
                    }
                } else {
                    logger.log(Level.SEVERE, "From is null or empty.");
                }
            } else {
                // Handle message_type here.
                String messageType = jGcmMessage.get("message_type").getAsString();
                if (messageType.equals("ack")) {
                    // Handle ACK. Here the ack is logged, you may want to further process the ACK at this
                    // point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("ACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("nack")) {
                    // Handle NACK. Here the nack is logged, you may want to further process the NACK at
                    // this point.
                    String messageId = jGcmMessage.get("message_id").getAsString();
                    logger.info("NACK received for message " + messageId + " from " + from);
                } else if (messageType.equals("control")) {
                    logger.info("Control message received.");
                    String controlType = jGcmMessage.get("control_type").getAsString();
                    if (controlType.equals("CONNECTION_DRAINING")) {
                        // Handle connection draining
                        // SmackCcsClient only maintains one connection the CCS to reduce complexity. A real
                        // world application should be capable of maintaining multiple connections to GCM,
                        // allowing the application to continue to onMessage for incoming messages on the
                        // draining connection and sending all new out going messages on a newly created
                        // connection.
                        logger.info("Current connection will be closed soon.");
                    } else {
                        // Currently the only control_type is CONNECTION_DRAINING, if new control messages
                        // are added they should be handled here.
                        logger.info("New control message has been received.");
                    }
                }
            }
        }
    };
    smackCcsClient.listen(stanzaListener, stanzaFilter);

}

From source file:br.com.saude.api.social.gcm.GcmServer.java

License:Open Source License

/**
 * Send Ack message back to CCS to acknowledged the receipt of the message with ID msg_id.
 *
 * @param to Registration token of the sender of the message being acknowledged.
 * @param msg_id ID of message being acknowledged.
 *///from w ww.  ja v a2  s.  co  m
private void sendAck(String to, String msg_id) {
    JsonObject jPayload = new JsonObject();
    jPayload.addProperty("to", to);
    jPayload.addProperty("message_id", msg_id);
    jPayload.addProperty("message_type", "ack");

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    final String payload = gson.toJson(jPayload);
    Stanza stanza = new Stanza() {
        @Override
        public CharSequence toXML() {
            return wrapWithXML(payload);
        }
    };

    logger.info("sending ack: " + stanza);
    smackCcsClient.sendStanza(stanza);
}