Example usage for com.google.gson JsonElement isJsonNull

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

Introduction

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

Prototype

public boolean isJsonNull() 

Source Link

Document

provides check for verifying if this element represents a null value or not.

Usage

From source file:com.kyloth.serleena.synchronization.kylothcloud.TrackEntityDeserializer.java

License:Open Source License

@Override
public TrackEntity deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    TrackEntity te = new TrackEntity();
    String idString = json.getAsJsonObject().get("id").getAsString();
    te.uuid = UUID.fromString(idString);
    te.name = json.getAsJsonObject().get("name").getAsString();
    te.checkpoints = new LinkedList<CheckpointEntity>();
    JsonArray cpoints = json.getAsJsonObject().get("checkPoints").getAsJsonArray();
    for (JsonElement cpoint : cpoints) {
        CheckpointEntity cp = new CheckpointEntity();
        cp.id = cpoint.getAsJsonObject().get("id").getAsInt();
        cp.point = new GeoPoint(cpoint.getAsJsonObject().get("latitude").getAsFloat(),
                cpoint.getAsJsonObject().get("longitude").getAsFloat());
        te.checkpoints.add(cp);//from  w w w. ja v a  2 s.c  o  m
    }
    te.telemetries = new LinkedList<TelemetryEntity>();
    JsonElement bestTele = json.getAsJsonObject().get("bestTelemetry");

    if (!bestTele.isJsonNull())
        te.telemetries.add(new TelemetryEntityDeserializer().deserialize(bestTele.getAsJsonObject(),
                TelemetryEntity.class, context));
    return te;
}

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.  j  av  a2 s. co  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 w w  .ja  v a 2  s .com

    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 w  w w .j a va 2s  . co  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.mediamath.terminalone.service.GetService.java

License:Apache License

/**
 * parses error response of Get operation.
 * //from w ww . j a va 2s  .  c  om
 * @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.utils.T1JsonToObjParser.java

License:Apache License

/**
 * Determines the Json Element type from the given response.
 * /* w  w w  .  j av  a  2  s .com*/
 * @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;
}

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

License:Apache License

private int getErrorElementType(String response) {
    int isArrayObj = 0; // 0 = null
    JsonParser parser = new JsonParser();
    JsonObject obj = parser.parse(response).getAsJsonObject();
    JsonElement errorElement = obj.get("errors");
    if (errorElement != null) {
        if (errorElement.isJsonNull()) {
            isArrayObj = 0; // null
        } else {// w w  w  .  jav a  2s.c o m
            isArrayObj = 2; // array
        }
    }
    return isArrayObj;
}

From source file:com.michaelfotiadis.crossyscore.core.data.parsers.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (!type.getRawType().equals(baseType)) {
        return null;
    }//  ww  w. j  a  v a 2  s .  c o  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }
    };
}

From source file:com.michaelfotiadis.steam.net.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//w  ww  .  j  a va2s.  co m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }
    };
}

From source file:com.microsoft.windowsazure.mobileservices.table.MobileServiceJsonTable.java

License:Open Source License

/**
 * Validates the Id property from a JsonObject on an Insert Action
 *
 * @param json The JsonObject to modify/*from  w ww  .  java  2 s  .  co  m*/
 */
private Object validateIdOnInsert(final JsonObject json) {
    // Remove id property if exists
    String[] idPropertyNames = new String[] { "id", "Id", "iD", "ID" };

    for (int i = 0; i < 4; i++) {
        String idProperty = idPropertyNames[i];

        if (json.has(idProperty)) {
            JsonElement idElement = json.get(idProperty);

            if (isStringType(idElement)) {
                String id = getStringValue(idElement);

                if (!isValidStringId(id)) {
                    throw new IllegalArgumentException(
                            "The entity to insert has an invalid string value on " + idProperty + " property.");
                }

                return id;
            } else if (isNumericType(idElement)) {
                long id = getNumericValue(idElement);

                if (!isDefaultNumericId(id)) {
                    throw new IllegalArgumentException("The entity to insert should not have a numeric "
                            + idProperty + " property defined.");
                }

                json.remove(idProperty);

                return id;

            } else if (idElement.isJsonNull()) {
                json.remove(idProperty);

                return null;

            } else {
                throw new IllegalArgumentException("The entity to insert should not have an " + idProperty
                        + " defined with an invalid value");
            }
        }
    }

    return null;
}