Example usage for com.google.gson JsonElement isJsonArray

List of usage examples for com.google.gson JsonElement isJsonArray

Introduction

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

Prototype

public boolean isJsonArray() 

Source Link

Document

provides check for verifying if this element is an array or not.

Usage

From source file:com.keydap.sparrow.SparrowClient.java

License:Apache License

private JsonObject keysToLower(JsonObject obj) {
    JsonObject tmp = new JsonObject();
    for (String key : obj.keySet()) {
        JsonElement je = obj.get(key);
        if (key.contains(":")) {
            JsonObject ext = keysToLower((JsonObject) je);
            tmp.add(key, ext);/*from w  w  w .ja v  a  2  s.c om*/
        } else {
            if (je.isJsonObject()) {
                je = keysToLower((JsonObject) je);
            } else if (je.isJsonArray()) {
                JsonArray arr = je.getAsJsonArray();
                for (int i = 0; i < arr.size(); i++) {
                    JsonElement item = arr.get(i);
                    if (item.isJsonObject()) {
                        item = keysToLower((JsonObject) item);
                        arr.set(i, item);
                    }
                }
            }

            tmp.add(key.toLowerCase(), je);
        }
    }

    return tmp;
}

From source file:com.kurento.kmf.jsonrpcconnector.internal.message.MessageUtils.java

License:Open Source License

private static <R> R convertJsonTo(JsonElement resultJsonObject, Class<R> resultClass) {

    if (resultJsonObject == null) {
        return null;
    }//from  ww  w.jav  a  2s  .  c  om

    R resultR = null;
    if (resultClass == String.class || resultClass == Boolean.class || resultClass == Character.class
            || Number.class.isAssignableFrom(resultClass) || resultClass.isPrimitive()) {

        JsonElement value;
        if (resultJsonObject.isJsonObject()) {

            Set<Entry<String, JsonElement>> properties = ((JsonObject) resultJsonObject).entrySet();

            if (properties.size() > 1) {

                Entry<String, JsonElement> prop = properties.iterator().next();

                log.warn(
                        "Converting a result with {} properties in a value"
                                + " of type {}. Selecting propoerty '{}'",
                        properties.size(), resultClass, prop.getKey());

                value = prop.getValue();

            } else if (properties.size() == 1) {
                value = properties.iterator().next().getValue();
            } else {
                value = null;
            }

        } else if (resultJsonObject.isJsonArray()) {
            JsonArray array = (JsonArray) resultJsonObject;
            if (array.size() > 1) {
                log.warn("Converting an array with elements in a value " + "of type. Selecting first element",
                        array.size(), resultClass);

            }

            value = array.get(0);
        } else {
            value = resultJsonObject;
        }

        resultR = getGson().fromJson(value, resultClass);
    } else {
        resultR = getGson().fromJson(resultJsonObject, resultClass);
    }
    return resultR;
}

From source file:com.ls.util.internal.ObjectComparator.java

License:Open Source License

private static @Nullable Object getDifferencesObject(JsonElement origin, JsonElement patched) {
    if (origin != null && origin.equals(patched)) {
        return UNCHANGED;
    }//from  w  w w  .ja  v  a  2 s.  c o  m

    if (patched == null || patched.isJsonNull()) {
        return null;
    }

    if (origin == null || origin.isJsonNull()) {
        return convertElementToStringRepresentation(patched);
    }

    if (origin.isJsonArray()) {
        if (patched.isJsonArray()) {
            return getDifferencesForArrays((JsonArray) origin, (JsonArray) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    if (origin.isJsonObject()) {
        if (patched.isJsonObject()) {
            return getDifferencesMapForObjects((JsonObject) origin, (JsonObject) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    if (origin.isJsonPrimitive()) {
        if (patched.isJsonPrimitive()) {
            return getDifferencesForPrimitives((JsonPrimitive) origin, (JsonPrimitive) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    return convertElementToStringRepresentation(patched);
}

From source file:com.ls.util.internal.ObjectComparator.java

License:Open Source License

private static Object convertElementToStringRepresentation(JsonElement source) {
    if (source.isJsonNull()) {
        return null;
    }//from   w ww .  j ava2  s. co m

    if (source.isJsonPrimitive()) {
        return source.toString();
    }

    if (source.isJsonObject()) {
        return getMapFromJsonElement((JsonObject) source);
    }

    if (source.isJsonArray()) {
        return getListFromJsonElement((JsonArray) source);
    }

    return null;
}

From source file:com.ls.util.ObjectComparator.java

License:Open Source License

@Nullable
private static Object getDifferencesObject(JsonElement origin, JsonElement patched) {
    if (origin != null && origin.equals(patched)) {
        return UNCHANGED;
    }/*from  ww w .j a va 2s. c om*/

    if (patched == null || patched.isJsonNull()) {
        return null;
    }

    if (origin == null || origin.isJsonNull()) {
        return convertElementToStringRepresentation(patched);
    }

    if (origin.isJsonArray()) {
        if (patched.isJsonArray()) {
            return getDifferencesForArrays((JsonArray) origin, (JsonArray) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    if (origin.isJsonObject()) {
        if (patched.isJsonObject()) {
            return getDifferencesMapForObjects((JsonObject) origin, (JsonObject) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    if (origin.isJsonPrimitive()) {
        if (patched.isJsonPrimitive()) {
            return getDifferencesForPrimitives((JsonPrimitive) origin, (JsonPrimitive) patched);
        } else {
            return convertElementToStringRepresentation(patched);
        }
    }

    return convertElementToStringRepresentation(patched);
}

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

License:Apache License

/**
 * parses error response of Get operation.
 * /*  w w w. j  a v a2s .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 . jav  a 2  s  . 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.PostService.java

License:Apache License

private <T extends T1Entity> JsonResponse<? extends T1Entity> parsePostData(String response,
        T1JsonToObjParser parser, T entity) throws ParseException {

    // parse the string to gson objs
    JsonResponse<? extends T1Entity> finalJsonResponse = null;
    JsonElement element = parser.getDataFromResponse(response);
    if (element != null) {
        if (element.isJsonArray()) {
            // do something
            JsonArray dataList = element.getAsJsonArray();

            String entityType;/*from ww  w  .  j a va  2s  .co  m*/
            if (dataList.size() > 0) {
                JsonElement data = dataList.get(0);
                if (data != null) {
                    JsonObject dataObj = data.getAsJsonObject();
                    if (dataObj != null) {
                        JsonElement entityTypeElem = dataObj.get("entity_type");
                        if (entityTypeElem != null) {
                            entityType = entityTypeElem.getAsString();
                            if (entityType != null && !entityType.isEmpty()) {
                                if (Constants.getListoFEntityType.get(entityType) != null) {
                                    finalJsonResponse = parser.parseJsonToObj(response,
                                            Constants.getListoFEntityType.get(entityType));
                                }
                            }
                        }
                    }
                }
            }

        } else if (element.isJsonObject()) {
            JsonObject obj = element.getAsJsonObject();
            JsonElement entityTypeElement = obj.get("entity_type");
            String entityType = entityTypeElement.getAsString();
            finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(entityType));
        }
    } else if (element == null) {
        if (entity != null) {
            finalJsonResponse = parser.parseJsonToObj(response,
                    Constants.getEntityType.get(entity.getEntityname().toLowerCase()));
            if (finalJsonResponse != null) {
                finalJsonResponse.setData(null);
            }
        }
    }
    return finalJsonResponse;
}

From source file:com.mediamath.terminalone.TerminalOne.java

License:Apache License

/**
 * parses the response to objects.//from w  w  w .  j  a va2  s.c o  m
 * 
 * @param response
 *          a valid JSON response string is required.
 * @param QueryCriteria
 *          a valid query object is required.
 * @return JsonResponse<? extends T1Entity> JsonResponse of type T is returned.
 * @throws ClientException
 *           a client exception is thrown if any error occurs.
 * @throws ParseException
 *           a parse exception is thrown when the response cannot be parsed.
 */
private <T extends T1Entity> JsonResponse<? extends T1Entity> parseGetData(String response, QueryCriteria query)
        throws ParseException, ClientException {
    T1JsonToObjParser parser = new T1JsonToObjParser();
    // parse the string to gson objs
    JsonResponse<? extends T1Entity> finalJsonResponse = null;
    JsonPostErrorResponse jsonPostErrorResponse = null;

    // check whether error present
    jsonPostErrorResponse = getService.jsonGetErrorResponseParser(response);
    // if no error
    if (jsonPostErrorResponse == null) {
        JsonElement element = parser.getDataFromResponse(response);
        if (element != null) {
            if (element.isJsonArray()) {
                // do something
                JsonArray dataList = element.getAsJsonArray();

                String entityType;
                if (dataList.size() > 0) {
                    JsonElement data = dataList.get(0);
                    if (data != null) {
                        JsonObject dataObj = data.getAsJsonObject();
                        if (dataObj != null) {
                            JsonElement entityTypeElem = dataObj.get("entity_type");
                            if (entityTypeElem != null) {
                                entityType = entityTypeElem.getAsString();
                                if (entityType != null && !entityType.isEmpty()) {
                                    if (Constants.getListoFEntityType.get(entityType) != null) {
                                        finalJsonResponse = parser.parseJsonToObj(response,
                                                Constants.getListoFEntityType.get(entityType));
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (query.collection != null) {
                        finalJsonResponse = parser.parseJsonToObj(response,
                                Constants.getListoFEntityType.get(query.collection.toLowerCase()));
                    }
                }

            } else if (element.isJsonObject()) {
                JsonObject obj = element.getAsJsonObject();
                JsonElement entityTypeElement = obj.get("entity_type");
                String entityType = (entityTypeElement != null) ? entityTypeElement.getAsString() : null;
                if (entityType != null && !entityType.equalsIgnoreCase("")) {
                    finalJsonResponse = parser.parseJsonToObj(response,
                            Constants.getEntityType.get(entityType));
                } else {
                    finalJsonResponse = parser.parseJsonToObj(response, new TypeToken<JsonResponse<Data>>() {
                    }.getType());
                }
            }
        } else if (element == null) {
            if (query.collection != null) {
                finalJsonResponse = parser.parseJsonToObj(response,
                        Constants.getEntityType.get(query.collection.toLowerCase()));
                if (finalJsonResponse != null) {
                    finalJsonResponse.setData(null);
                }
            }
        }
    } else {
        postService.throwExceptions(jsonPostErrorResponse);
    }
    return finalJsonResponse;
}

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

License:Apache License

/**
 * Determines the Json Element type from the given response.
 * /*from  w w w.  ja  v a  2s . co m*/
 * @param response
 *          JSON response string.
 * 
 * @return int value <br>
 *         0 = null body<br>
 *         1 = Json Element is of type Object. <br>
 *         2 = Json Element is of type Array.
 * 
 */
public int getJsonElementType(String response) {
    int isArrayObj = 0; // 0 = null
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();
    JsonElement element = obj.get("data");
    if (element != null) {
        if (element.isJsonArray()) {
            isArrayObj = 2; // array object
        } else if (element.isJsonObject()) {
            isArrayObj = 1; // single object
        } else if (element.isJsonNull()) {
            isArrayObj = 0; // nothing.
        }
    } else {
        isArrayObj = getErrorElementType(response);
    }
    return isArrayObj;
}