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:com.github.jneat.mybatis.JsonElementTypeHandler.java

License:Open Source License

@Override
public JsonElement getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String jsonSource = rs.getString(columnIndex);
    if (jsonSource != null) {
        return fromString(jsonSource);
    }/*from  w  w  w .j a  va 2  s  .  c om*/
    return JsonNull.INSTANCE;
}

From source file:com.github.jneat.mybatis.JsonElementTypeHandler.java

License:Open Source License

@Override
public JsonElement getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String jsonSource = cs.getString(columnIndex);
    if (jsonSource != null) {
        return fromString(jsonSource);
    }/*from  w w w  . j  a  va  2  s  .co  m*/
    return JsonNull.INSTANCE;
}

From source file:com.github.jsdossier.Config.java

License:Apache License

/**
 * Returns this configuration object as a JSON object.
 *//*  www .  j a  va2  s .  com*/
JsonObject toJson() {
    JsonObject json = new JsonObject();
    json.add("output", new JsonPrimitive(output.toString()));
    json.add("sources", toJsonArray(srcs));
    json.add("modules", toJsonArray(modules));
    json.add("externs", toJsonArray(externs));
    json.add("excludes", toJsonArray(excludes));
    json.add("typeFilters", toJsonArray(typeFilters));
    json.add("stripModulePrefix", new JsonPrimitive(modulePrefix.toString()));
    json.add("readme", readme.isPresent() ? new JsonPrimitive(readme.get().toString()) : JsonNull.INSTANCE);
    json.addProperty("strict", strict);
    json.addProperty("useMarkdown", useMarkdown);
    json.addProperty("language", language.name());

    JsonArray pages = new JsonArray();
    for (Page page : customPages) {
        pages.add(page.toJson());
    }
    json.add("customPages", pages);

    return json;
}

From source file:com.gs.reladomo.serial.gson.GsonReladomoSerialWriter.java

License:Apache License

@Override
public void writeNull(GsonRelodomoSerialContext context, String attributeName, Class type) {
    context.getCurrentResultAsObject().add(attributeName, JsonNull.INSTANCE);
}

From source file:com.ibm.g11n.pipeline.resfilter.impl.JsonResource.java

License:Open Source License

@Override
public void write(OutputStream outStream, LanguageBundle languageBundle, FilterOptions options)
        throws IOException, ResourceFilterException {
    // extracts key value pairs in original sequence order
    List<ResourceString> resStrings = languageBundle.getSortedResourceStrings();

    JsonObject output = new JsonObject();
    JsonObject top_level;/*from   ww  w.j a v  a  2 s  .co  m*/

    if (this instanceof GlobalizeJsResource) {
        String resLanguageCode = languageBundle.getEmbeddedLanguageCode();
        if (resLanguageCode == null || resLanguageCode.isEmpty()) {
            throw new ResourceFilterException(
                    "Missing resource language code in the specified language bundle.");
        }
        top_level = new JsonObject();
        top_level.add(resLanguageCode, output);
    } else {
        top_level = output;
    }

    for (ResourceString res : resStrings) {
        String key = res.getKey();
        List<KeyPiece> keyPieces = splitKeyPieces(key);
        JsonElement current = output;
        for (int i = 0; i < keyPieces.size(); i++) {
            if (i + 1 < keyPieces.size()) { // There is structure under this
                                            // key piece
                if (current.isJsonObject()) {
                    JsonObject currentObject = current.getAsJsonObject();
                    if (!currentObject.has(keyPieces.get(i).keyValue)) {
                        if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) {
                            currentObject.add(keyPieces.get(i).keyValue, new JsonArray());
                        } else {
                            currentObject.add(keyPieces.get(i).keyValue, new JsonObject());
                        }
                    }
                    current = currentObject.get(keyPieces.get(i).keyValue);
                } else {
                    JsonArray currentArray = current.getAsJsonArray();
                    Integer idx = Integer.valueOf(keyPieces.get(i).keyValue);
                    for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) {
                        currentArray.add(JsonNull.INSTANCE);
                    }
                    if (currentArray.get(idx).isJsonNull()) {
                        if (keyPieces.get(i + 1).keyType == JsonToken.BEGIN_ARRAY) {
                            currentArray.set(idx, new JsonArray());
                        } else {
                            currentArray.set(idx, new JsonObject());
                        }
                    }
                    current = currentArray.get(idx);
                }
            } else { // This is the leaf node
                if (keyPieces.get(i).keyType == JsonToken.BEGIN_ARRAY) {
                    JsonArray currentArray = current.getAsJsonArray();
                    Integer idx = Integer.valueOf(keyPieces.get(i).keyValue);
                    JsonPrimitive e = new JsonPrimitive(res.getValue());
                    for (int arrayIndex = currentArray.size(); arrayIndex <= idx; arrayIndex++) {
                        currentArray.add(JsonNull.INSTANCE);
                    }
                    current.getAsJsonArray().set(idx, e);
                } else {
                    current.getAsJsonObject().addProperty(keyPieces.get(i).keyValue, res.getValue());
                }
            }
        }
    }
    try (OutputStreamWriter writer = new OutputStreamWriter(new BufferedOutputStream(outStream),
            StandardCharsets.UTF_8)) {
        new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create().toJson(top_level, writer);
    }
}

From source file:com.ibm.streamsx.topology.builder.BOperatorInvocation.java

License:Open Source License

@Override
public JsonObject _complete() {
    final JsonObject json = super._complete();

    if (outputs != null) {
        JsonArray oa = new JsonArray();
        // outputs array in java is in port order.
        for (int i = 0; i < outputs.size(); i++)
            oa.add(JsonNull.INSTANCE); // will be overwritten with port info
        for (BOutputPort output : outputs.values())
            oa.set(output.index(), output._complete());
        json.add("outputs", oa);
    }//from   ww w.j av a  2  s.  c o  m

    if (inputs != null) {
        JsonArray ia = new JsonArray();
        for (int i = 0; i < inputs.size(); i++)
            ia.add(JsonNull.INSTANCE); // will be overwritten with port info
        for (BInputPort input : inputs)
            ia.set(input.index(), input._complete());
        json.add("inputs", ia);
    }

    return json;
}

From source file:com.ibm.watson.developer_cloud.util.DateSerializer.java

License:Open Source License

@Override
// DateSerializer.serialize() is NOT thread safe because of the underlying SimpleDateFormats.
public synchronized JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
    return src == null ? JsonNull.INSTANCE : new JsonPrimitive(utc.format(src));
}

From source file:com.impetus.client.couchdb.CouchDBObjectMapper.java

License:Apache License

/**
 * Gets the entity from json.// ww w  . ja va2 s. c om
 * 
 * @param entityClass
 *            the entity class
 * @param m
 *            the m
 * @param jsonObj
 *            the json obj
 * @param relations
 *            the relations
 * @param kunderaMetadata
 *            the kundera metadata
 * @return the entity from json
 */
static Object getEntityFromJson(Class<?> entityClass, EntityMetadata m, JsonObject jsonObj,
        List<String> relations, final KunderaMetadata kunderaMetadata) {// Entity object
    Object entity = null;

    // Map to hold property-name=>foreign-entity relations
    try {
        entity = KunderaCoreUtils.createNewInstance(entityClass);

        // Populate primary key column
        JsonElement rowKey = jsonObj.get(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
        if (rowKey == null) {
            return null;
        }
        Class<?> idClass = null;
        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
                .getMetamodel(m.getPersistenceUnit());
        Map<String, Object> relationValue = null;
        idClass = m.getIdAttribute().getJavaType();
        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType())) {
            Class javaType = m.getIdAttribute().getBindableJavaType();
            PropertyAccessorHelper.setId(entity, m, getObjectFromJson(rowKey.getAsJsonObject(), javaType,
                    metaModel.embeddable(javaType).getAttributes()));
        } else {
            PropertyAccessorHelper.setId(entity, m, PropertyAccessorHelper.fromSourceToTargetClass(idClass,
                    String.class, rowKey.getAsString()));
        }

        EntityType entityType = metaModel.entity(entityClass);

        String discriminatorColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();

        Set<Attribute> columns = entityType.getAttributes();

        for (Attribute column : columns) {
            JsonElement value = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
            if (!column.equals(m.getIdAttribute())
                    && !((AbstractAttribute) column).getJPAColumnName().equals(discriminatorColumn)
                    && value != null && !value.equals(JsonNull.INSTANCE)) {
                String fieldName = ((AbstractAttribute) column).getJPAColumnName();

                Class javaType = ((AbstractAttribute) column).getBindableJavaType();
                if (metaModel.isEmbeddable(javaType)) {
                    onViaEmbeddable(entityType, column, m, entity, metaModel.embeddable(javaType), jsonObj);
                } else if (!column.isAssociation()) {
                    setFieldValue(entity, column, value);
                } else if (relations != null) {
                    if (relationValue == null) {
                        relationValue = new HashMap<String, Object>();
                    }

                    if (relations.contains(fieldName)
                            && !fieldName.equals(((AbstractAttribute) m.getIdAttribute()).getJPAColumnName())) {
                        JsonElement colValue = jsonObj.get(((AbstractAttribute) column).getJPAColumnName());
                        if (colValue != null) {
                            String colFieldName = m.getFieldName(fieldName);
                            Attribute attribute = entityType.getAttribute(colFieldName);
                            EntityMetadata relationMetadata = KunderaMetadataManager
                                    .getEntityMetadata(kunderaMetadata, attribute.getJavaType());
                            Object colVal = PropertyAccessorHelper.fromSourceToTargetClass(
                                    relationMetadata.getIdAttribute().getJavaType(), String.class,
                                    colValue.getAsString());
                            relationValue.put(fieldName, colVal);
                        }
                    }
                }
            }
        }
        if (relationValue != null && !relationValue.isEmpty()) {
            EnhanceEntity e = new EnhanceEntity(entity, PropertyAccessorHelper.getId(entity, m), relationValue);
            return e;
        } else {
            return entity;
        }
    } catch (Exception e) {
        log.error("Error while extracting entity object from json, caused by {}.", e);
        throw new KunderaException(e);
    }
}

From source file:com.lithium.luces.Luces.java

License:Apache License

@Override
public Object getFieldValue(String name, String value) {
    if (typeMap == null && errIfMappingNull) {
        throw new IllegalStateException(
                String.format("Mapping is null, but required. [name = %1$s, value = %2$s]", name, value));
    }/*  w  w w  .  j  a va2 s .  co  m*/
    final ParseType parseType;
    ParseType temp;
    if (typeMap == null || (temp = typeMap.get(name)) == null) {
        log.warn("Field {} has no type association, parsing \"{}\" as a string", name, value);
        parseType = ParseType.STRING;
    } else {
        parseType = temp;
    }
    String fieldValue = value;
    if (null == fieldValue || (useNull && fieldValue.trim().isEmpty())) {
        return JsonNull.INSTANCE;
    }
    Object parsedValue;
    try {
        switch (parseType) {
        case BYTE:
            // FALL THROUGH
        case SHORT:
            // FALL THROUGH
        case INTEGER:
            // FALL THROUGH
        case LONG:
            fieldValue = fieldValue.trim();
            fieldValue = (useDefaults && fieldValue.isEmpty()) ? "0" : fieldValue;
            parsedValue = Long.parseLong(fieldValue);
            break;
        case FLOAT:
            // FALL THROUGH
        case DOUBLE:
            fieldValue = fieldValue.trim();
            fieldValue = (useDefaults && fieldValue.isEmpty()) ? "0.0" : fieldValue;
            parsedValue = Double.parseDouble(fieldValue);
            break;
        case BOOLEAN:
            fieldValue = fieldValue.trim();
            // anything that doesn't match the string "true" ignoring case evaluates to false
            parsedValue = Boolean.parseBoolean(fieldValue);
            break;
        default: // leave as untrimmed string
            parsedValue = fieldValue;
            break;
        }
    } catch (NumberFormatException ex) {
        throw new NumberFormatException("Error parsing " + name + " field: " + ex.getMessage());
    }

    return parsedValue;
}

From source file:com.microsoft.windowsazure.mobileservices.table.serialization.LongSerializer.java

License:Open Source License

/**
 * Serializes a Long instance to a JsonElement, verifying the maximum and
 * minimum allowed values//from w  w w.  j ava2s  .c  o m
 */
@Override
public JsonElement serialize(Long element, Type type, JsonSerializationContext ctx) {
    Long maxAllowedValue = 0x0020000000000000L;
    Long minAllowedValue = Long.valueOf(0xFFE0000000000000L);
    if (element != null) {
        if (element > maxAllowedValue || element < minAllowedValue) {
            throw new IllegalArgumentException(
                    "Long value must be between " + minAllowedValue + " and " + maxAllowedValue);
        } else {
            return new JsonPrimitive(element);
        }
    } else {
        return JsonNull.INSTANCE;
    }
}