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.logisticsShop.utils.JsonUtil.java

License:Apache License

/**
 * ????? {@code JSON} ??/*from   ww w .  ja  v  a2  s  .c o  m*/
 * <p />
 * <b>??????<code>"{}"</code>???<code>"[]"</code> </b>
 * 
 * @param target
 *            ?
 * @param targetType
 *            ?
 * @param isSerializeNulls
 *            ???{@code null} ?
 * @param version
 *            ??
 * @param datePattern
 *            ???
 * @param excludesFieldsWithoutExpose
 *            ??{@literal @Expose} ?
 * @return ?{@code JSON} ??
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

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//from   w w  w .j  av a  2s  .  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.mediamath.terminalone.service.GetService.java

License:Apache License

/**
 * parses error response of Get operation.
 * /*  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 w w. j a  va 2s. c  om
 * @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.
 * /*from   w  ww. ja v a 2 s .co 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;
}

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

License:Apache License

/**
 * parses the meta data response for a particular report query.
 * /*from   w ww.  ja  va2  s  .  c  o  m*/
 * @param response
 *          requires JSON response.
 * @return MetaData object.
 */
public MetaData parseReportMetaResponse(String response) {

    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
    Gson gson = builder.create();
    MetaData data = gson.fromJson(response, MetaData.class);

    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();
    JsonElement reportsElement = obj.get("structure");

    JsonObject dimensionObj = reportsElement.getAsJsonObject().get("dimensions").getAsJsonObject();
    JsonObject metricsObj = reportsElement.getAsJsonObject().get("metrics").getAsJsonObject();
    JsonObject timefieldObj = reportsElement.getAsJsonObject().get("time_field").getAsJsonObject();

    // dimensions
    if (dimensionObj != null) {
        MetaDimensions dimensions = new MetaDimensions();
        HashMap<String, MetaDimensionData> dimensionsInfoMap = new HashMap<String, MetaDimensionData>();

        for (Entry<String, JsonElement> a : dimensionObj.entrySet()) {
            String key = a.getKey();
            MetaDimensionData value = gson.fromJson(a.getValue(), MetaDimensionData.class);
            dimensionsInfoMap.put(key, value);
        }

        dimensions.setDimensionsInfoMap(dimensionsInfoMap);
        data.getStructure().setDimensions(dimensions);
    }

    // metrics
    if (metricsObj != null) {
        MetaMetrics metrics = new MetaMetrics();
        HashMap<String, MetricsData> metricsMap = new HashMap<String, MetricsData>();

        for (Entry<String, JsonElement> a : metricsObj.entrySet()) {
            String key = a.getKey();
            MetricsData value = gson.fromJson(a.getValue(), MetricsData.class);
            metricsMap.put(key, value);
        }

        metrics.setMetricsMap(metricsMap);
        data.getStructure().setMetrics(metrics);
    }

    // time_field
    if (timefieldObj != null) {

        TimeField timefield = new TimeField();
        HashMap<String, TimeInterval> timeFieldMap = new HashMap<String, TimeInterval>();

        for (Entry<String, JsonElement> a : timefieldObj.entrySet()) {
            String key = a.getKey();
            TimeInterval value = gson.fromJson(a.getValue(), TimeInterval.class);
            timeFieldMap.put(key, value);
        }

        timefield.setData(timeFieldMap);
        data.getStructure().setTimeField(timefield);
    }

    return data;
    // end
}

From source file:com.mediamath.terminalone.utils.T1JsonToObjParser.java

License:Apache License

/**
 * parses 3pas creative upload response string to TPASCreativeUpload object.
 * /*from   w  w w. j a va 2s .  c  o  m*/
 * @param json3PasCreativeResponseString
 *          required response string
 * @return TPASCreativeUpload object.
 */
public TPASCreativeUpload parse3PasCreativeUploadResponseTOObj(String json3PasCreativeResponseString) {
    TPASCreativeUpload response = null;
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
    builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
    Gson gson = builder.create();
    response = gson.fromJson(json3PasCreativeResponseString, TPASCreativeUpload.class);
    return response;
}

From source file:com.mediamath.terminalone.utils.T1JsonToObjParser.java

License:Apache License

/**
 * parses T1AS creative asset upload response to TOneASCreativeAssetsUpload entity.
 * /*from  ww  w.j a v  a  2s  . c  o m*/
 * @param jsonT1CAUesponse
 *          response string.
 * @return TOneASCreativeAssetsUpload object.
 */
public TOneASCreativeAssetsUpload parseTOneASCreativeAssetsUploadResponseTOObj(String jsonT1CAUesponse) {
    TOneASCreativeAssetsUpload response = null;
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES);
    builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
    Gson gson = builder.create();
    response = gson.fromJson(jsonT1CAUesponse, TOneASCreativeAssetsUpload.class);
    return response;
}

From source file:com.mediamath.terminalone.utils.T1JsonToObjParser.java

License:Apache License

/**
 * parses the response of second call to T1AS creative assets approve api call.
 * /*  ww  w  .  j av  a 2  s .c om*/
 * @param pResponse
 *          requires a response string.
 * @return JsonResponse<? extends T1Entity> returns an entity of type T.
 */
public JsonResponse<? extends T1Entity> parseTOneASCreativeAssetsApproveResponse(String pResponse) {
    JsonResponse<? extends T1Entity> response = null;

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

    Type type = new TypeToken<JsonResponse<ArrayList<TOneASCreativeAssetsApproveResponse>>>() {
    }.getType();

    response = gson.fromJson(pResponse, type);
    return response;

}

From source file:com.mediamath.terminalone.utils.T1JsonToObjParser.java

License:Apache License

/**
 * parse video creative to VideoCreativeReponse entity.
 * /*  ww  w  .j  a v a2 s  .  c om*/
 * @param pResponse
 *          response String.
 * @return VideoCreativeResponse object.
 */
public VideoCreativeResponse parseVideoCreative(String pResponse) {
    VideoCreativeResponse response = null;

    GsonBuilder builder = new GsonBuilder();
    builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS);
    Gson gson = builder.create();
    response = gson.fromJson(pResponse, VideoCreativeResponse.class);

    return response;
}