Example usage for com.google.gson JsonDeserializer JsonDeserializer

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

Introduction

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

Prototype

JsonDeserializer

Source Link

Usage

From source file:com.luan.thermospy.android.core.rest.StartLogSessionReq.java

License:Open Source License

private JSONObject getJsonObject() {
    List<LogSession> logSessionsList = new ArrayList<LogSession>();
    // Creates the json object which will manage the information received
    GsonBuilder builder = new GsonBuilder();

    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }/*from   w  w  w.  j a va2 s .c  o m*/
    });

    Gson gson = builder.create();

    try {
        return new JSONObject(gson.toJson(mLogSession, LogSession.class));
    } catch (JSONException | JsonIOException e) {
        return null;
    }
}

From source file:com.luan.thermospy.android.core.rest.StartLogSessionReq.java

License:Open Source License

@Override
public void onOkResponse(JSONObject response) {
    GsonBuilder builder = new GsonBuilder();

    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }// www .jav a  2 s.  c  o m
    });

    Gson gson = builder.create();
    try {
        LogSession logSession = gson.fromJson(response.toString(), LogSession.class);
        mListener.onStartLogSessionRecv(logSession);
    } catch (JsonSyntaxException ex) {
        mListener.onStartLogSessionError();
    }
}

From source file:com.luan.thermospy.android.core.rest.StopLogSessionReq.java

License:Open Source License

@Override
public void onOkResponse(JSONObject response) {
    GsonBuilder builder = new GsonBuilder();

    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong());
        }//  w  w w  .j  a  v  a  2s  .c o  m
    });

    Gson gson = builder.create();
    try {
        LogSession logSession = gson.fromJson(response.toString(), LogSession.class);
        mListener.onStopLogSessionRecv(logSession);
    } catch (JsonSyntaxException ex) {
        mListener.onStopLogSessionError();
    }
}

From source file:com.meltmedia.cadmium.cli.HistoryCommand.java

License:Apache License

/**
 * Retrieves the history of a Cadmium site.
 * /*from ww  w  . j  a  v a2 s.  c  om*/
 * @param siteUri The uri of a cadmium site.
 * @param limit The maximum number of history entries to retrieve or if set to -1 tells the site to retrieve all history.
 * @param filter If true filters out the non revertable history entries.
 * @param token The Github API token to pass to the Cadmium site for authentication.
 * 
 * @return A list of {@link HistoryEntry} Objects that are populated with the history returned from the Cadmium site.
 * 
 * @throws URISyntaxException
 * @throws IOException
 * @throws ClientProtocolException
 * @throws Exception
 */
public static List<HistoryEntry> getHistory(String siteUri, int limit, boolean filter, String token)
        throws URISyntaxException, IOException, ClientProtocolException, Exception {

    if (!siteUri.endsWith("/system/history")) {
        siteUri += "/system/history";
    }

    List<HistoryEntry> history = null;

    HttpClient httpClient = httpClient();
    HttpGet get = null;
    try {
        URIBuilder uriBuilder = new URIBuilder(siteUri);
        if (limit > 0) {
            uriBuilder.addParameter("limit", limit + "");
        }
        if (filter) {
            uriBuilder.addParameter("filter", filter + "");
        }
        URI uri = uriBuilder.build();
        get = new HttpGet(uri);
        addAuthHeader(token, get);

        HttpResponse resp = httpClient.execute(get);
        if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = resp.getEntity();
            if (entity.getContentType().getValue().equals("application/json")) {
                String responseContent = EntityUtils.toString(entity);
                Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {

                    @Override
                    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext ctx)
                            throws JsonParseException {
                        return new Date(json.getAsLong());
                    }

                }).create();
                history = gson.fromJson(responseContent, new TypeToken<List<HistoryEntry>>() {
                }.getType());
            } else {
                System.err
                        .println("Invalid response content type [" + entity.getContentType().getValue() + "]");
                System.exit(1);
            }
        } else {
            System.err.println("Request failed due to a [" + resp.getStatusLine().getStatusCode() + ":"
                    + resp.getStatusLine().getReasonPhrase() + "] response from the remote server.");
            System.exit(1);
        }
    } finally {
        if (get != null) {
            get.releaseConnection();
        }
    }
    return history;
}

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

License:Open Source License

/**
 * Creates an instance of Gson./* ww  w  . java  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();
}

From source file:com.onedrive.sdk.serializer.GsonFactory.java

License:Open Source License

/**
 * Creates an instance of Gson.//w  w w . j av a2s . c  o 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.opencarte.db.Parser.java

public DataSet[] getDataSet() {
    DataSet[] dataSet = null;/*from ww  w .jav  a  2 s.  c om*/

    JsonDeserializer<DataSet> datasetDes = new JsonDeserializer<DataSet>() {

        @Override
        public DataSet deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            JsonObject deserialize = je.getAsJsonObject();
            Geometry geo = new Geometry(deserialize.get("geometry").getAsJsonObject().get("type").getAsString(),
                    deserialize.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray().get(1)
                            .getAsDouble(),
                    deserialize.get("geometry").getAsJsonObject().get("coordinates").getAsJsonArray().get(0)
                            .getAsDouble());
            return new DataSet(deserialize.get("datasetid").getAsString(),
                    deserialize.get("recordid").getAsString(), geo);
        }
    };
    builder.registerTypeAdapter(DataSet.class, datasetDes);
    gson = builder.create();

    try {
        dataSet = gson.fromJson(fileContent, DataSet[].class);
    } catch (JsonParseException ex) {
        System.out.println("Invalid JSON: " + ex.getMessage());
    }
    return dataSet;
}

From source file:com.opencarte.db.TaxisParser.java

@Override
public ParisTaxi[] getDataSet() {

    //GsonBuilder myBuilder;
    //Gson myGson; 
    DataSet[] dataset = super.getDataSet();
    ParisTaxi[] parisTaxis = new ParisTaxi[dataset.length];
    PrisTaxiAux[] prisTaxiAux = new PrisTaxiAux[dataset.length];

    JsonDeserializer<PrisTaxiAux> paristaxisauxDes = new JsonDeserializer<PrisTaxiAux>() {

        @Override/*from  ww  w. j  a  va  2  s .co m*/
        public PrisTaxiAux deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            JsonObject deserialize = je.getAsJsonObject();
            return new PrisTaxiAux(deserialize.get("fields").getAsJsonObject().get("city").getAsString(),
                    deserialize.get("fields").getAsJsonObject().get("address").getAsString(),
                    //deserialize.get("fields").getAsJsonObject().get("address_precision").getAsString(), 
                    deserialize.get("fields").getAsJsonObject().get("station_name").getAsString(),
                    deserialize.get("fields").getAsJsonObject().get("zip_code").getAsInt());
        }
    };
    myBuilder.registerTypeAdapter(PrisTaxiAux.class, paristaxisauxDes);
    myGson = myBuilder.create();

    try {
        prisTaxiAux = myGson.fromJson(myFileContent, PrisTaxiAux[].class);
    } catch (JsonParseException ex) {
        System.out.println("Invalid JSON: " + ex.getMessage());
    }

    for (int i = 0; i < dataset.length; i++) {
        //parisTaxis[i].setDatasetid(dataset[i].getDatasetid());
        parisTaxis[i] = new ParisTaxi(dataset[i].getDatasetid(), dataset[i].getRecordid(),
                dataset[i].getGeometry(), prisTaxiAux[i]);// TaxietGeometry(dataset[i].getGeometry());
        //parisTaxis[i].setFields();
    }

    return parisTaxis;
}

From source file:com.opencarte.db.VotesParser.java

@Override
public VotePoints[] getDataSet() {

    //GsonBuilder myBuilder;
    //Gson myGson; 
    DataSet[] dataset = super.getDataSet();
    VotePoints[] votePoints = new VotePoints[dataset.length];
    VotePointsAux[] votepointsaux = new VotePointsAux[dataset.length];

    JsonDeserializer<VotePointsAux> votepointsauxDes = new JsonDeserializer<VotePointsAux>() {

        @Override//from w w  w  . j  a v a 2s .c  o m
        public VotePointsAux deserialize(JsonElement je, Type type, JsonDeserializationContext jdc)
                throws JsonParseException {
            JsonObject deserialize = je.getAsJsonObject();
            return new VotePointsAux(
                    deserialize.get("fields").getAsJsonObject().get("equipement").getAsString(),
                    deserialize.get("fields").getAsJsonObject().get("adresse").getAsString());
        }
    };
    myBuilder.registerTypeAdapter(VotePointsAux.class, votepointsauxDes);
    myyGson = myBuilder.create();

    try {
        votepointsaux = myyGson.fromJson(myFileContent, VotePointsAux[].class);
    } catch (JsonParseException ex) {
        System.out.println("Invalid JSON: " + ex.getMessage());
    }

    for (int i = 0; i < dataset.length; i++) {
        //parisTaxis[i].setDatasetid(dataset[i].getDatasetid());
        votePoints[i] = new VotePoints(dataset[i].getDatasetid(), dataset[i].getRecordid(),
                dataset[i].getGeometry(), votepointsaux[i]);// TaxietGeometry(dataset[i].getGeometry());
        //parisTaxis[i].setFields();
    }

    return votePoints;
}

From source file:com.qualcomm.robotcore.hardware.LynxModuleMetaList.java

License:Open Source License

public static LynxModuleMetaList fromSerializationString(String serialization) {
    JsonDeserializer deserializer = new JsonDeserializer() {
        @Override/*from w  w  w  . j  a va  2  s  .  co  m*/
        public Object deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            return context.deserialize(json, LynxModuleMeta.class);
        }
    };

    Gson gson = new GsonBuilder().registerTypeAdapter(RobotCoreLynxModule.class, deserializer).create();

    return gson.fromJson(serialization, LynxModuleMetaList.class);
}