Example usage for com.google.gson GsonBuilder create

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

Introduction

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

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

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());
        }/*from  ww w  .  j a  va 2s  .  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 ww  .j  a va  2s . co  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.magenta.servlets.UserService.java

@Path("/check")
@PUT//from  ww w.  j  av a  2  s.c om
public Response checkUser(@QueryParam("name") String userName, @Context HttpServletRequest request) {

    HttpSession session = request.getSession();

    User user = userEJB.findByName(userName);

    // Gson gson = new Gson();
    Map<String, String> map = new Hashtable<String, String>();
    map.put("authorized", "true");

    String json = "";

    GsonBuilder gsonBuilder = new GsonBuilder();
    new GraphAdapterBuilder().addType(Task.class).registerOn(gsonBuilder);
    Gson gson = gsonBuilder.create();
    if (null != user) {
        cur_user = user;

        session.setAttribute("user", cur_user);
        //              map.put("tasks",gson.toJson(cur_user.getTasks()));

        json = gson.toJson(cur_user);

        return Response.ok().entity(json).build();
    } else {

        user = userEJB.create(userName);
        cur_user = user;

        session.setAttribute("user", cur_user);

        json = gson.toJson(cur_user);
        return Response.status(Response.Status.CREATED).entity(json).build();
    }

}

From source file:com.magenta.servlets.UserService.java

@Path("/taskinfo")
@GET/*from   w ww  . ja va  2  s.c o  m*/
public Response loadTasksInfo(@QueryParam("userId") Integer userId) {
    User user = userEJB.findByPrimaryKey(userId);
    Collection<Task> taskList = taskEJB.findByUser(user);

    GsonBuilder gsonBuilder = new GsonBuilder();
    new GraphAdapterBuilder().addType(Task.class).registerOn(gsonBuilder);

    return Response.ok().entity(gsonBuilder.create().toJson(taskList)).build();
}

From source file:com.magnet.android.mms.request.MagnetGsonFactory.java

License:Open Source License

/**
 * Create a new instance of Gson with registered adapters if needed
 * @return//  w w w.  jav a2s  . c  o  m
 */
public static Gson createMagnetGson() {
    GsonBuilder gb = new GsonBuilder();
    // Date - Use ZULU format
    gb.setDateFormat(SimpleParamHelper.sDateTimeFormat.toPattern());

    return gb.create();
}

From source file:com.mapr.storm.SpoutState.java

License:Apache License

public static SpoutState fromString(String serialized) {
    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(SpoutState.class, new SpoutStateAdapter());
    return gson.create().fromJson(serialized, SpoutState.class);
}

From source file:com.mediamath.terminalone.service.GetService.java

License:Apache License

/**
 * parses error response of Get operation.
 * /*from  w  w  w.ja  va  2s.c  o m*/
 * @param responseStr
 *          string.
 * @return JsonPostErrorResponse object.
 */
public JsonPostErrorResponse jsonGetErrorResponseParser(String responseStr) {
    JsonParser parser1 = new JsonParser();
    JsonObject obj = parser1.parse(responseStr).getAsJsonObject();

    JsonElement errorsElement = obj.get("errors");
    JsonElement errorElement = obj.get("error");
    JsonElement metaElement = obj.get("meta");

    JsonPostErrorResponse errorResponse = null;

    if (errorsElement != null || errorElement != null) {
        errorResponse = new JsonPostErrorResponse();
        GsonBuilder builder = new GsonBuilder();
        builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
        builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);

        Gson gson = builder.create();

        if (errorsElement != null) {
            if (errorsElement.isJsonNull()) {

            } else if (errorsElement.isJsonObject()) {
                T1Error errors = gson.fromJson(errorsElement, T1Error.class);
                // specific to video creatives
                if (errors != null && errors.getContent() == null && errors.getField() == null
                        && errors.getFieldError() == null && errors.getMessage() == null) {

                    GsonBuilder videoBuilder = new GsonBuilder();
                    videoBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
                    videoBuilder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);

                    Gson vidgson = videoBuilder.create();

                    errors = vidgson.fromJson(errorsElement, T1Error.class);
                }
                errorResponse.setErrors(errors);
            } else if (errorsElement.isJsonArray()) {
                JsonArray array = errorsElement.getAsJsonArray();
                JsonArray newArray = new JsonArray();

                for (int i = 0; i < array.size(); i++) {
                    if (!(array.get(i) instanceof JsonPrimitive)) {
                        newArray.add(array.get(i));

                    }
                }
                if (newArray.size() > 0) {
                    errorsElement = newArray;
                    Type type = new TypeToken<ArrayList<T1Error>>() {
                    }.getType();
                    List<T1Error> errors = gson.fromJson(errorsElement, type);
                    errorResponse.setErrors(errors);
                }
            }
        }

        if (errorElement != null) {
            T1Error error = gson.fromJson(errorElement, T1Error.class);
            errorResponse.setError(error);
        }

        if (metaElement != null) {
            T1Meta meta = gson.fromJson(metaElement, T1Meta.class);
            errorResponse.setMeta(meta);
        }
    }

    return errorResponse;
}

From source file:com.mediamath.terminalone.service.PostService.java

License:Apache License

/**
 * parses error response of a POST activity.
 * /*from  w ww . j  a  v  a  2 s  . c  o m*/
 * @param responseStr
 *          requires a response JSON string
 * @param responseObj
 *          requires a Response object.
 * @return JsonPostErrorResponse entity.
 */
public JsonPostErrorResponse jsonPostErrorResponseParser(String responseStr, Response responseObj) {
    JsonParser parser1 = new JsonParser();
    JsonObject obj = parser1.parse(responseStr).getAsJsonObject();

    JsonElement errorsElement = obj.get("errors");
    JsonElement errorElement = obj.get("error");
    JsonElement metaElement = obj.get("meta");

    JsonPostErrorResponse errorResponse = null;

    if (errorsElement != null || errorElement != null
            || (responseObj != null && responseObj.getStatus() == 403 && metaElement != null)) {
        errorResponse = new JsonPostErrorResponse();
        GsonBuilder builder = new GsonBuilder();
        builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
        builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);

        Gson gson = builder.create();

        if (errorsElement != null) {
            if (errorsElement.isJsonObject()) {
                T1Error errors = gson.fromJson(errorsElement, T1Error.class);
                // specific to video creatives
                if (errors != null && errors.getContent() == null && errors.getField() == null
                        && errors.getFieldError() == null && errors.getMessage() == null) {

                    GsonBuilder videoBuilder = new GsonBuilder();
                    videoBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
                    videoBuilder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);

                    Gson vidgson = videoBuilder.create();

                    errors = vidgson.fromJson(errorsElement, T1Error.class);
                }
                errorResponse.setErrors(errors);
            } else if (errorsElement.isJsonArray()) {
                JsonArray array = errorsElement.getAsJsonArray();
                JsonArray newArray = new JsonArray();

                for (int i = 0; i < array.size(); i++) {
                    if (!(array.get(i) instanceof JsonPrimitive)) {
                        newArray.add(array.get(i));

                    }
                }
                if (newArray.size() > 0) {
                    errorsElement = newArray;
                    Type type = new TypeToken<ArrayList<T1Error>>() {
                    }.getType();
                    List<T1Error> errors = gson.fromJson(errorsElement, type);
                    errorResponse.setErrors(errors);
                }
            }
        }

        if (errorElement != null) {
            T1Error error = gson.fromJson(errorElement, T1Error.class);
            errorResponse.setError(error);
        }

        if (metaElement != null) {
            if (responseObj != null && responseObj.getStatus() == 403) {
                T1Meta meta = gson.fromJson(metaElement, T1Meta.class);
                errorResponse.setMeta(meta);
            }
        }
    }

    return errorResponse;
}

From source file:com.mediamath.terminalone.service.ReportService.java

License:Apache License

/**
 * this method parses meta query response.
 * // w  ww .  j av  a 2  s.c  o  m
 * @param response
 *          requires the JSON response.
 * @return JsonResponse<? extends T1Entity> returns JsonResponse of type T.
 * 
 */
public JsonResponse<? extends T1Entity> parseMetaResponse(String response) {
    JsonParser parser = new JsonParser();
    JsonResponse<Meta> finalResponse = null;
    JsonObject obj = parser.parse(response).getAsJsonObject();

    JsonElement reportsElement = obj.get("reports");
    JsonObject reportsObj = reportsElement.getAsJsonObject();

    if (reportsObj != null) {

        Meta meta = new Meta();
        Type type = new TypeToken<MetaData>() {
        }.getType();
        HashMap<String, MetaData> metaData = new HashMap<String, MetaData>();

        GsonBuilder builder = new GsonBuilder();
        builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
        Gson gson = builder.create();

        for (Entry<String, JsonElement> a : reportsObj.entrySet()) {
            String key = a.getKey();
            MetaData value = gson.fromJson(a.getValue(), type);
            metaData.put(key, value);
        }
        meta.setMetaData(metaData);
        finalResponse = new JsonResponse<Meta>(meta);
    }

    return finalResponse;
}