Example usage for com.google.gson JsonNull INSTANCE

List of usage examples for com.google.gson JsonNull INSTANCE

Introduction

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

Prototype

JsonNull INSTANCE

To view the source code for com.google.gson JsonNull INSTANCE.

Click Source Link

Document

singleton for JsonNull

Usage

From source file:qa.qcri.nadeef.web.sql.SQLUtil.java

License:Open Source License

public static JsonObject queryToJson(ResultSet rs, boolean includeHeader) throws RuntimeException {
    try {/*from w ww.j  a  va 2 s  .co m*/
        ResultSetMetaData metaData = rs.getMetaData();
        int ncol = metaData.getColumnCount();
        JsonObject queryObject = new JsonObject();
        if (includeHeader) {
            JsonArray array = new JsonArray();
            for (int i = 1; i <= ncol; i++)
                array.add(new JsonPrimitive(metaData.getColumnName(i)));

            queryObject.add("schema", array);
        }

        JsonArray data = new JsonArray();
        while (rs.next()) {
            JsonArray entry = new JsonArray();
            for (int i = 1; i <= ncol; i++) {
                Object obj = rs.getObject(i);
                if (obj != null)
                    entry.add(new JsonPrimitive(obj.toString()));
                else
                    entry.add(JsonNull.INSTANCE);
            }
            data.add(entry);
        }

        queryObject.add("data", data);
        return queryObject;
    } catch (SQLException ex) {
        tracer.err("Exception", ex);
        throw new RuntimeException(ex);
    }
}

From source file:rpc.server.data.JSONSerializer.java

License:Open Source License

private JsonElement toJsonElement(Object object) {
    if (object == null) {
        return JsonNull.INSTANCE;
    }//from   www. j  ava  2s.  co  m

    // Boolean
    Boolean asBoolean = Utils.isBoolean(object);
    if (asBoolean != null) {
        return new JsonPrimitive(asBoolean);
    }

    // Integer
    Integer asInteger = Utils.isInteger(object);
    if (asInteger != null) {
        return new JsonPrimitive(asInteger);
    }

    // Long
    Long asLong = Utils.isLong(object);
    if (asLong != null) {
        return new JsonPrimitive(asLong);
    }

    // Float
    Float asFloat = Utils.isFloat(object);
    if (asFloat != null) {
        return new JsonPrimitive(asFloat);
    }

    // Double
    Double asDouble = Utils.isDouble(object);
    if (asDouble != null) {
        return new JsonPrimitive(asDouble);
    }

    // String
    String asString = Utils.isString(object);
    if (asString != null) {
        return new JsonPrimitive(asString);
    }

    // Enum
    Enum asEnum = Utils.isEnum(object);
    if (asEnum != null) {
        return new JsonPrimitive(asEnum.toString());
    }

    // Serializable
    Serializable asSerializable = Utils.isSerializable(object);
    if (asSerializable != null) {
        JsonObject jsonObject = new JsonObject();

        for (String field : asSerializable.fields().keySet()) {
            Object value = asSerializable.get(field);
            jsonObject.add(field, toJsonElement(value));
        }

        return jsonObject;
    }

    // List
    List<Object> asSerializableList = Utils.isSerializableList(object);
    if (asSerializableList != null) {
        JsonArray jsonArray = new JsonArray();

        for (Object item : asSerializableList) {
            jsonArray.add(toJsonElement(item));
        }

        return jsonArray;
    }

    // Map
    Map<Object, Object> asSerializableMap = Utils.isSerializableMap(object);
    if (asSerializableMap != null) {
        JsonObject jsonObject = new JsonObject();

        for (Map.Entry<Object, Object> entry : asSerializableMap.entrySet()) {

            Object keyObject = entry.getKey();
            Object valueObject = entry.getValue();

            String key = null;

            String keyAsString = Utils.isString(keyObject);
            if (keyAsString != null) {
                key = keyAsString;
            }

            Enum keyAsEnum = Utils.isEnum(keyObject);
            if (keyAsEnum != null) {
                key = keyAsEnum.toString();
            }

            jsonObject.add(key, toJsonElement(valueObject));
        }

        return jsonObject;
    }

    return null;
}

From source file:ru.koluch.JsonFilesBuilder.java

License:Apache License

private void writeDict(JsonArrayWriter dictWriter, JsonArrayWriter paradigmsWriter,
        JsonArrayWriter prefixesWriter, Dictionary dict) throws IOException {

    for (List<ParadigmRule> paradigm : dict.paradigmList) {
        JsonArray rulesJson = new JsonArray();
        for (ParadigmRule paradigmRule : paradigm) {
            JsonArray ruleJson = new JsonArray();
            ruleJson.add(paradigmRule.ending.<JsonElement>map(JsonPrimitive::new).orElse(JsonNull.INSTANCE));
            ruleJson.add(paradigmRule.ancode);
            ruleJson.add(paradigmRule.prefix.<JsonElement>map(JsonPrimitive::new).orElse(JsonNull.INSTANCE));
            rulesJson.add(ruleJson);/*  www  .j  av a 2 s. co m*/
        }
        paradigmsWriter.write(rulesJson);
    }

    for (LexemeRec lexemeRec : dict.lexemeRecs) {
        JsonArray lexemeRecJson = new JsonArray();
        lexemeRecJson.add(lexemeRec.basis);
        lexemeRecJson.add(lexemeRec.paradigmIndex);
        lexemeRecJson.add(lexemeRec.accentParadigmIndex);
        lexemeRecJson.add(lexemeRec.userSessionIndex);
        lexemeRecJson.add(lexemeRec.ancode.<JsonElement>map(JsonPrimitive::new).orElse(JsonNull.INSTANCE));
        lexemeRecJson.add(
                lexemeRec.prefixParadigmIndex.<JsonElement>map(JsonPrimitive::new).orElse(JsonNull.INSTANCE));
        dictWriter.write(lexemeRecJson);
    }

    for (String prefix : dict.prefixeParadigmList) {
        prefixesWriter.write(new JsonPrimitive(prefix));
    }
}

From source file:se.sperber.cryson.serialization.CrysonSerializer.java

License:Apache License

private void augmentJsonElement(Object rawObject, JsonElement jsonElement, Set<String> associationsToInclude) {
    Object object = HibernateProxyTypeAdapter.initializeAndUnproxy(rawObject);
    try {/* w ww .  jav a2 s  .  c o m*/
        if (object instanceof Collection) {
            int ix = 0;
            JsonArray jsonArray = jsonElement.getAsJsonArray();
            for (Object subObject : (Collection) object) {
                JsonElement subJsonElement = jsonArray.get(ix++);
                augmentJsonElement(subObject, subJsonElement, associationsToInclude);
            }
        } else {
            jsonElement.getAsJsonObject().add("crysonEntityClass",
                    new JsonPrimitive(object.getClass().getSimpleName()));

            if (object instanceof Restrictable) {
                if (!((Restrictable) object)
                        .isReadableBy(SecurityContextHolder.getContext().getAuthentication())) {
                    transformJsonObjectToUnauthorizedEntity(jsonElement.getAsJsonObject());
                    return;
                }
            }

            for (Map.Entry<String, JsonElement> member : jsonElement.getAsJsonObject().entrySet()) {
                if (member.getValue().isJsonObject() || member.getValue().isJsonArray()) {
                    Field field = reflectionHelper.getField(object, member.getKey());
                    field.setAccessible(true);
                    augmentJsonElement(field.get(object), member.getValue(),
                            subAssociationsToInclude(associationsToInclude, member.getKey()));
                }
            }

            Set<Field> userTypeFields = getUserTypeFields(object.getClass());
            for (Field field : userTypeFields) {
                Object fieldValue = field.get(object);
                if (fieldValue != null && Map.class.isAssignableFrom(field.getType())) {
                    JsonElement jsonFieldValue = gsonAllInclusive.toJsonTree(fieldValue);
                    jsonElement.getAsJsonObject().add(field.getName() + "_cryson_usertype", jsonFieldValue);
                }
            }

            Set<Method> transientGetters = reflectionHelper
                    .getAllDeclaredVirtualAttributeGetters(object.getClass());
            for (Method method : transientGetters) {
                Object methodValue = method.invoke(object);
                JsonElement jsonFieldValue = gsonAllInclusive.toJsonTree(methodValue);
                jsonElement.getAsJsonObject()
                        .add(reflectionHelper.getAttributeNameFromGetterName(method.getName()), jsonFieldValue);
            }

            Set<Field> fields = getLazyFields(object.getClass());
            for (Field field : fields) {
                Object fieldValue = field.get(object);
                if (fieldValue != null && associationsToInclude.contains(field.getName())) {
                    JsonElement fieldValueJsonElement = gson.toJsonTree(fieldValue);
                    augmentJsonElement(fieldValue, fieldValueJsonElement,
                            subAssociationsToInclude(associationsToInclude, field.getName()));
                    jsonElement.getAsJsonObject().add(field.getName(), fieldValueJsonElement);
                } else if (fieldValue != null) {
                    if (fieldValue instanceof Collection) {
                        JsonArray primaryKeyArray = new JsonArray();
                        for (Object subElement : (Collection) fieldValue) {
                            primaryKeyArray.add(new JsonPrimitive(reflectionHelper.getPrimaryKey(subElement)));
                        }
                        jsonElement.getAsJsonObject().add(field.getName() + "_cryson_ids", primaryKeyArray);
                    } else {
                        jsonElement.getAsJsonObject().addProperty(field.getName() + "_cryson_id",
                                reflectionHelper.getPrimaryKey(fieldValue));
                    }
                } else {
                    jsonElement.getAsJsonObject().add(field.getName() + "_cryson_id", JsonNull.INSTANCE);
                }
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:se.sperber.cryson.serialization.CrysonSerializer.java

License:Apache License

private <T> T augmentEntity(T object, JsonElement jsonElement, Map<Long, Long> replacedTemporaryIds) {
    try {/*from w  w  w. j  a  v  a 2s. c  om*/
        Set<Map.Entry<String, JsonElement>> attributes = jsonElement.getAsJsonObject().entrySet();
        for (Map.Entry<String, JsonElement> attribute : attributes) {
            if (attribute.getKey().endsWith("_cryson_id")) {
                String attributeName = attribute.getKey().split("_cryson_id")[0];
                Field field = reflectionHelper.getField(object, attributeName);
                if (field != null) {
                    if (attribute.getValue() != JsonNull.INSTANCE) {
                        Object placeHolderObject = field.getType().newInstance();
                        reflectionHelper.setPrimaryKey(placeHolderObject, primaryKeyForReplacementObject(
                                attribute.getValue().getAsLong(), replacedTemporaryIds));
                        field.set(object, placeHolderObject);
                    }
                }
            } else if (attribute.getKey().endsWith("_cryson_ids")) {
                String attributeName = attribute.getKey().split("_cryson_ids")[0];
                Field field = reflectionHelper.getField(object, attributeName);
                if (field != null) {
                    Iterator<JsonElement> attributeIterator = attribute.getValue().getAsJsonArray().iterator();
                    Collection<Object> placeHolderObjects = emptyCollectionForField(field);
                    while (attributeIterator.hasNext()) {
                        JsonElement attributeValue = attributeIterator.next();
                        Object placeHolderObject = ((Class) ((ParameterizedType) (field.getGenericType()))
                                .getActualTypeArguments()[0]).newInstance();
                        reflectionHelper.setPrimaryKey(placeHolderObject, primaryKeyForReplacementObject(
                                attributeValue.getAsLong(), replacedTemporaryIds));
                        placeHolderObjects.add(placeHolderObject);
                    }
                    field.set(object, placeHolderObjects);
                }
            } else if (attribute.getKey().endsWith("_cryson_usertype")) {
                String attributeName = attribute.getKey().split("_cryson_usertype")[0];
                Field field = reflectionHelper.getField(object, attributeName);
                if (field != null && Map.class.isAssignableFrom(field.getType())) {
                    Map<Object, Object> placeHolderObjects = new HashMap<Object, Object>();
                    for (Map.Entry<String, JsonElement> valueEntry : attribute.getValue().getAsJsonObject()
                            .entrySet()) {
                        String placeHolderKeyObject = valueEntry.getKey();
                        Object placeHolderValueObject = gson.fromJson(valueEntry.getValue(), Object.class); // Support string->string maps only
                        placeHolderObjects.put(placeHolderKeyObject, placeHolderValueObject);
                    }
                    field.set(object, placeHolderObjects);
                }
            }
        }
        return object;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:tech.sirwellington.alchemy.http.Generators.java

License:Apache License

static AlchemyGenerator<JsonNull> jsonNull()

{
    return () -> JsonNull.INSTANCE;
}

From source file:tech.sirwellington.alchemy.http.HttpVerbImpl.java

License:Apache License

private JsonElement extractJsonFromResponse(HttpRequest matchingRequest,
        org.apache.http.HttpResponse apacheResponse) throws JsonException, JsonParseException {
    if (apacheResponse.getEntity() == null) {
        return JsonNull.INSTANCE;
    }//from  w  w w .  j a  v  a 2  s .  com

    HttpEntity entity = apacheResponse.getEntity();

    String contentType = entity.getContentType().getValue();

    /*
     * We used to care what the content type was, and had a check for it here.
     * But perhaps it's better if we don't care what the content type is, as long as we can read it as a String.
     */
    String responseString = null;
    try (final InputStream istream = entity.getContent()) {
        byte[] rawBytes = ByteStreams.toByteArray(istream);
        responseString = new String(rawBytes, Charsets.UTF_8);
    } catch (Exception ex) {
        LOG.error("Failed to read entity from request", ex);
        throw new AlchemyHttpException(matchingRequest, "Failed to read response from server", ex);
    }

    if (Strings.isNullOrEmpty(responseString)) {
        return JsonNull.INSTANCE;
    } else {
        if (contentType.contains("application/json")) {
            return gson.fromJson(responseString, JsonElement.class);
        } else {
            return gson.toJsonTree(responseString);
        }
    }
}

From source file:tech.sirwellington.alchemy.http.Step2Impl.java

License:Apache License

@Override
public AlchemyRequest.Step3 nothing() {
    HttpRequest newRequest = HttpRequest.Builder.from(request).usingBody(JsonNull.INSTANCE).build();

    return stateMachine.jumpToStep3(newRequest);
}

From source file:uk.co.real_logic.sbe.codec.java.MethodValuesSerializer.java

License:Apache License

JsonElement serialize(final Object object, final boolean visitIterable)
        throws InvocationTargetException, IllegalAccessException {
    if (object == null) {
        return JsonNull.INSTANCE;
    }//from   w  w  w . jav a 2 s  .c o  m

    final Class<?> clazz = object.getClass();
    if (Number.class.isAssignableFrom(clazz)) {
        return new JsonPrimitive((Number) object);
    } else if (clazz == String.class) {
        return new JsonPrimitive((String) object);
    } else if (clazz == Boolean.class) {
        return new JsonPrimitive((Boolean) object);
    } else if (object instanceof Enum) {
        return new JsonPrimitive(((Enum<?>) object).name());
    } else if (clazz.isArray()) {
        final JsonArray result = new JsonArray();
        final int len = Array.getLength(object);
        for (int i = 0; i < len; ++i) {
            result.add(serialize(Array.get(object, i)));
        }

        return result;
    } else if (visitIterable && Iterable.class.isAssignableFrom(clazz)) {
        final Iterator<?> iter = ((Iterable<?>) object).iterator();
        final JsonArray result = new JsonArray();
        while (iter.hasNext()) {
            result.add(serialize(iter.next(), false));
        }

        return result;
    } else if (Map.class.isAssignableFrom(clazz)) {
        final JsonObject result = new JsonObject();
        for (final Map.Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) {
            result.add(entry.getKey().toString(), serialize(entry.getValue()));
        }

        return result;
    } else {
        return serializeObject(object, clazz);
    }
}