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:org.apache.gobblin.converter.csv.CsvToJsonConverterV2.java

License:Apache License

@VisibleForTesting
JsonObject createOutput(JsonArray outputSchema, String[] inputRecord) {
    Preconditions.checkArgument(outputSchema.size() == inputRecord.length,
            "# of columns mismatch. Input " + inputRecord.length + " , output: " + outputSchema.size());
    JsonObject outputRecord = new JsonObject();

    for (int i = 0; i < outputSchema.size(); i++) {
        JsonObject field = outputSchema.get(i).getAsJsonObject();
        String key = field.get(COLUMN_NAME_KEY).getAsString();

        if (StringUtils.isEmpty(inputRecord[i]) || JSON_NULL_VAL.equalsIgnoreCase(inputRecord[i])) {
            outputRecord.add(key, JsonNull.INSTANCE);
        } else {//from   w w  w . j ava 2 s.c  om
            outputRecord.add(key, convertValue(inputRecord[i], field.getAsJsonObject(DATA_TYPE_KEY)));
        }
    }

    return outputRecord;
}

From source file:org.apache.gobblin.converter.csv.CsvToJsonConverterV2.java

License:Apache License

@VisibleForTesting
JsonObject createOutput(JsonArray outputSchema, String[] inputRecord, List<String> customOrder) {

    Preconditions.checkArgument(outputSchema.size() == customOrder.size(),
            "# of columns mismatch. Input " + outputSchema.size() + " , output: " + customOrder.size());
    JsonObject outputRecord = new JsonObject();
    Iterator<JsonElement> outputSchemaIterator = outputSchema.iterator();
    Iterator<String> customOrderIterator = customOrder.iterator();

    while (outputSchemaIterator.hasNext() && customOrderIterator.hasNext()) {
        JsonObject field = outputSchemaIterator.next().getAsJsonObject();
        String key = field.get(COLUMN_NAME_KEY).getAsString();
        int i = Integer.parseInt(customOrderIterator.next());
        Preconditions.checkArgument(i < inputRecord.length,
                "Index out of bound detected in customer order. Index: " + i + " , # of CSV columns: "
                        + inputRecord.length);
        if (i < 0 || null == inputRecord[i] || JSON_NULL_VAL.equalsIgnoreCase(inputRecord[i])) {
            outputRecord.add(key, JsonNull.INSTANCE);
            continue;
        }//from   w w  w .j  av  a  2  s  .c  o  m
        outputRecord.add(key, convertValue(inputRecord[i], field.getAsJsonObject(DATA_TYPE_KEY)));
    }

    return outputRecord;
}

From source file:org.apache.gobblin.converter.grok.GrokToJsonConverter.java

License:Apache License

@VisibleForTesting
JsonObject createOutput(JsonArray outputSchema, String inputRecord) throws DataConversionException {
    JsonObject outputRecord = new JsonObject();

    Match gm = grok.match(inputRecord);//from ww  w  .  j  a  v a  2  s .c  o  m
    gm.captures();

    JsonElement capturesJson = JSON_PARSER.parse(gm.toJson());

    for (JsonElement anOutputSchema : outputSchema) {
        JsonObject outputSchemaJsonObject = anOutputSchema.getAsJsonObject();
        String key = outputSchemaJsonObject.get(COLUMN_NAME_KEY).getAsString();
        String type = outputSchemaJsonObject.getAsJsonObject(DATA_TYPE).get(TYPE_KEY).getAsString();

        if (isFieldNull(capturesJson, key)) {
            if (!outputSchemaJsonObject.get(NULLABLE).getAsBoolean()) {
                throw new DataConversionException(
                        "Field " + key + " is null or not exists but it is non-nullable by the schema.");
            }
            outputRecord.add(key, JsonNull.INSTANCE);
        } else {
            JsonElement jsonElement = capturesJson.getAsJsonObject().get(key);
            switch (type) {
            case "int":
                outputRecord.addProperty(key, jsonElement.getAsInt());
                break;
            case "long":
                outputRecord.addProperty(key, jsonElement.getAsLong());
                break;
            case "double":
                outputRecord.addProperty(key, jsonElement.getAsDouble());
                break;
            case "float":
                outputRecord.addProperty(key, jsonElement.getAsFloat());
                break;
            case "boolean":
                outputRecord.addProperty(key, jsonElement.getAsBoolean());
                break;
            case "string":
            default:
                outputRecord.addProperty(key, jsonElement.getAsString());
            }
        }
    }
    return outputRecord;
}

From source file:org.apache.gobblin.converter.json.JsonStringToJsonIntermediateConverter.java

License:Apache License

/**
 * Parses a provided JsonObject input using the provided JsonArray schema into
 * a JsonObject.//  ww w  . java  2s. c  o  m
 * @param record
 * @param schema
 * @return
 * @throws DataConversionException
 */
private JsonObject parse(JsonObject record, JsonSchema schema) throws DataConversionException {
    JsonObject output = new JsonObject();
    for (int i = 0; i < schema.fieldsCount(); i++) {
        JsonSchema schemaElement = schema.getFieldSchemaAt(i);
        String columnKey = schemaElement.getColumnName();
        JsonElement parsed;
        if (!record.has(columnKey)) {
            output.add(columnKey, JsonNull.INSTANCE);
            continue;
        }

        JsonElement columnValue = record.get(columnKey);
        switch (schemaElement.getType()) {
        case UNION:
            parsed = parseUnionType(schemaElement, columnValue);
            break;
        case ENUM:
            parsed = parseEnumType(schemaElement, columnValue);
            break;
        default:
            if (columnValue.isJsonArray()) {
                parsed = parseJsonArrayType(schemaElement, columnValue);
            } else if (columnValue.isJsonObject()) {
                parsed = parseJsonObjectType(schemaElement, columnValue);
            } else {
                parsed = parsePrimitiveType(schemaElement, columnValue);
            }
        }
        output.add(columnKey, parsed);
    }
    return output;
}

From source file:org.apache.gobblin.converter.json.JsonStringToJsonIntermediateConverter.java

License:Apache License

/**
 * Parses JsonObject type values/*from w w  w  .j  a va  2  s  .c o m*/
 * @param value
 * @return
 * @throws DataConversionException
 */
private JsonElement parseJsonObjectType(JsonSchema schema, JsonElement value) throws DataConversionException {
    JsonSchema valuesWithinDataType = schema.getValuesWithinDataType();
    if (schema.isType(MAP)) {
        if (Type.isPrimitive(valuesWithinDataType.getType())) {
            return value;
        }

        JsonObject map = new JsonObject();
        for (Entry<String, JsonElement> mapEntry : value.getAsJsonObject().entrySet()) {
            JsonElement mapValue = mapEntry.getValue();
            map.add(mapEntry.getKey(), parse(mapValue, valuesWithinDataType));
        }
        return map;
    } else if (schema.isType(RECORD)) {
        JsonSchema schemaArray = valuesWithinDataType.getValuesWithinDataType();
        return parse((JsonObject) value, schemaArray);
    } else {
        return JsonNull.INSTANCE;
    }
}

From source file:org.apache.gobblin.converter.json.JsonStringToJsonIntermediateConverter.java

License:Apache License

/**
 * Parses primitive types//from  w w  w .jav a 2 s.  co m
 * @param schema
 * @param value
 * @return
 * @throws DataConversionException
 */
private JsonElement parsePrimitiveType(JsonSchema schema, JsonElement value) throws DataConversionException {

    if ((schema.isType(NULL) || schema.isNullable()) && value.isJsonNull()) {
        return JsonNull.INSTANCE;
    }

    if ((schema.isType(NULL) && !value.isJsonNull()) || (!schema.isType(NULL) && value.isJsonNull())) {
        throw new DataConversionException(
                "Type mismatch for " + value.toString() + " of type " + schema.getDataTypes().toString());
    }

    if (schema.isType(FIXED)) {
        int expectedSize = schema.getSizeOfFixedData();
        if (value.getAsString().length() == expectedSize) {
            return value;
        } else {
            throw new DataConversionException(
                    "Fixed type value is not same as defined value expected fieldsCount: " + expectedSize);
        }
    } else {
        return value;
    }
}

From source file:org.apache.tajo.json.CommonGsonHelper.java

License:Apache License

/**
 * A helper method that gets a JSON object member value after making sure it exists and has a valid value. Useful when
 * a member value should present to proceed.
 * @param object A JSON object to get a member value from
 * @param memberName The name of a member to get value of
 * @return {@link JsonElement} value read from the given member
 * @throws JsonParseException When the specified member does not exist or have a value.
 *//*from  www  .  jav  a  2  s. c om*/
public static JsonElement getOrDie(JsonObject object, String memberName) throws JsonParseException {
    if (object.has(memberName)) {
        JsonElement element = object.get(memberName);
        if (!JsonNull.INSTANCE.equals(element)) {
            return element;
        }
    }
    throw new JsonParseException("Field '" + memberName + "' not found in JSON object '" + object + "'");
}

From source file:org.apache.tika.metadata.serialization.JsonMetadataSerializer.java

License:Apache License

/**
 * Serializes a Metadata object into effectively Map<String, String[]>.
 * /*from w  ww .jav  a  2 s.c o  m*/
 * @param metadata object to serialize
 * @param type (ignored)
 * @param context (ignored)
 * @return JsonElement with key/value(s) pairs or JsonNull if metadata is null.
 */
@Override
public JsonElement serialize(Metadata metadata, Type type, JsonSerializationContext context) {
    if (metadata == null) {
        return JsonNull.INSTANCE;
    }
    String[] names = getNames(metadata);
    if (names == null) {
        return JsonNull.INSTANCE;
    }

    JsonObject root = new JsonObject();

    for (String n : names) {

        String[] vals = metadata.getValues(n);
        if (vals == null) {
            //silently skip
            continue;
        }

        if (vals.length == 1) {
            root.addProperty(n, vals[0]);
        } else {
            JsonArray jArr = new JsonArray();
            for (int i = 0; i < vals.length; i++) {
                jArr.add(new JsonPrimitive(vals[i]));
            }
            root.add(n, jArr);
        }
    }
    return root;
}

From source file:org.apache.twill.internal.json.ILoggingEventSerializer.java

License:Apache License

@Override
public JsonElement serialize(ILoggingEvent event, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject json = new JsonObject();
    json.addProperty("name", event.getLoggerName());
    json.addProperty("host", hostname);
    json.addProperty("timestamp", Long.toString(event.getTimeStamp()));
    json.addProperty("level", event.getLevel().toString());
    json.addProperty("className", classNameConverter.convert(event));
    json.addProperty("method", methodConverter.convert(event));
    json.addProperty("file", fileConverter.convert(event));
    json.addProperty("line", lineConverter.convert(event));
    json.addProperty("thread", event.getThreadName());
    json.addProperty("message", event.getFormattedMessage());
    json.addProperty("runnableName", runnableName);
    if (event.getThrowableProxy() == null) {
        json.add("throwable", JsonNull.INSTANCE);
    } else {/*from w ww  . ja va2 s  . c  om*/
        json.add("throwable",
                context.serialize(new DefaultLogThrowable(event.getThrowableProxy()), LogThrowable.class));
    }

    return json;
}

From source file:org.ballerinalang.composer.service.ballerina.parser.service.BallerinaParserService.java

License:Open Source License

public static JsonElement generateJSON(Node node, Map<String, Node> anonStructs)
        throws InvocationTargetException, IllegalAccessException {
    if (node == null) {
        return JsonNull.INSTANCE;
    }/*from www  .java2s  .  co m*/
    Set<Method> methods = ClassUtils.getAllInterfaces(node.getClass()).stream()
            .flatMap(aClass -> Arrays.stream(aClass.getMethods())).collect(Collectors.toSet());
    JsonObject nodeJson = new JsonObject();

    JsonArray wsJsonArray = new JsonArray();
    Set<Whitespace> ws = node.getWS();
    if (ws != null && !ws.isEmpty()) {
        for (Whitespace whitespace : ws) {
            JsonObject wsJson = new JsonObject();
            wsJson.addProperty("ws", whitespace.getWs());
            wsJson.addProperty("i", whitespace.getIndex());
            wsJson.addProperty("text", whitespace.getPrevious());
            wsJson.addProperty("static", whitespace.isStatic());
            wsJsonArray.add(wsJson);
        }
        nodeJson.add("ws", wsJsonArray);
    }
    Diagnostic.DiagnosticPosition position = node.getPosition();
    if (position != null) {
        JsonObject positionJson = new JsonObject();
        positionJson.addProperty("startColumn", position.getStartColumn());
        positionJson.addProperty("startLine", position.getStartLine());
        positionJson.addProperty("endColumn", position.getEndColumn());
        positionJson.addProperty("endLine", position.getEndLine());
        nodeJson.add("position", positionJson);
    }

    /* Virtual props */

    JsonArray type = getType(node);
    if (type != null) {
        nodeJson.add(SYMBOL_TYPE, type);
    }
    if (node.getKind() == NodeKind.INVOCATION) {
        assert node instanceof BLangInvocation : node.getClass();
        BLangInvocation invocation = (BLangInvocation) node;
        if (invocation.symbol != null && invocation.symbol.kind != null) {
            nodeJson.addProperty(INVOCATION_TYPE, invocation.symbol.kind.toString());
        }
    }

    for (Method m : methods) {
        String name = m.getName();

        if (name.equals("getWS") || name.equals("getPosition")) {
            continue;
        }

        String jsonName;
        if (name.startsWith("get")) {
            jsonName = toJsonName(name, 3);
        } else if (name.startsWith("is")) {
            jsonName = toJsonName(name, 2);
        } else {
            continue;
        }

        Object prop = m.invoke(node);

        /* Literal class - This class is escaped in backend to address cases like "ss\"" and 8.0 and null */
        if (node.getKind() == NodeKind.LITERAL && "value".equals(jsonName)) {
            if (prop instanceof String) {
                nodeJson.addProperty(jsonName, '"' + StringEscapeUtils.escapeJava((String) prop) + '"');
                nodeJson.addProperty(UNESCAPED_VALUE, String.valueOf(prop));
            } else {
                nodeJson.addProperty(jsonName, String.valueOf(prop));
            }
            continue;
        }

        if (node.getKind() == NodeKind.ANNOTATION && node instanceof BLangAnnotation) {
            JsonArray attachmentPoints = new JsonArray();
            ((BLangAnnotation) node).getAttachPoints().stream().map(AttachPoint::getValue)
                    .map(JsonPrimitive::new).forEach(attachmentPoints::add);
            nodeJson.add("attachmentPoints", attachmentPoints);
        }
        // TODO: revisit logic for user defined types
        //            if (node.getKind() == NodeKind.USER_DEFINED_TYPE && jsonName.equals("typeName")) {
        //                IdentifierNode typeNode = (IdentifierNode) prop;
        //                Node structNode;
        //                if (typeNode.getValue().startsWith("$anonStruct$") &&
        //                        (structNode = anonStructs.remove(typeNode.getValue())) != null) {
        //                    JsonObject anonStruct = generateJSON(structNode, anonStructs).getAsJsonObject();
        //                    anonStruct.addProperty("anonStruct", true);
        //                    nodeJson.add("anonStruct", anonStruct);
        //                    continue;
        //                }
        //            }

        if (prop instanceof List && jsonName.equals("types")) {
            // Currently we don't need any Symbols for the UI. So skipping for now.
            continue;
        }

        /* Node classes */
        if (prop instanceof Node) {
            nodeJson.add(jsonName, generateJSON((Node) prop, anonStructs));
        } else if (prop instanceof List) {
            List listProp = (List) prop;
            JsonArray listPropJson = new JsonArray();
            nodeJson.add(jsonName, listPropJson);
            for (Object listPropItem : listProp) {
                if (listPropItem instanceof Node) {
                    /* Remove top level anon func and struct */
                    if (node.getKind() == NodeKind.COMPILATION_UNIT) {
                        if (listPropItem instanceof BLangFunction
                                && (((BLangFunction) listPropItem)).name.value.startsWith("$lambda$")) {
                            continue;
                        }
                    }
                    listPropJson.add(generateJSON((Node) listPropItem, anonStructs));
                } else {
                    logger.debug("Can't serialize " + jsonName + ", has a an array of " + listPropItem);
                }
            }

            /* Runtime model classes */
        } else if (prop instanceof Set && jsonName.equals("flags")) {
            Set flags = (Set) prop;
            for (Flag flag : Flag.values()) {
                nodeJson.addProperty(StringUtils.lowerCase(flag.toString()), flags.contains(flag));
            }
        } else if (prop instanceof Set) {
            // TODO : limit this else if to getInputs getOutputs of transform.
            Set vars = (Set) prop;
            JsonArray listVarJson = new JsonArray();
            nodeJson.add(jsonName, listVarJson);
            for (Object obj : vars) {
                listVarJson.add(obj.toString());
            }
        } else if (prop instanceof NodeKind) {
            String kindName = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, prop.toString());
            nodeJson.addProperty(jsonName, kindName);
        } else if (prop instanceof OperatorKind) {
            nodeJson.addProperty(jsonName, prop.toString());

            /* Generic classes */
        } else if (prop instanceof String) {
            nodeJson.addProperty(jsonName, (String) prop);
        } else if (prop instanceof Number) {
            nodeJson.addProperty(jsonName, (Number) prop);
        } else if (prop instanceof Boolean) {
            nodeJson.addProperty(jsonName, (Boolean) prop);
        } else if (prop instanceof Enum) {
            nodeJson.addProperty(jsonName, StringUtils.lowerCase(((Enum) prop).name()));
        } else if (prop instanceof int[]) {
            int[] intArray = ((int[]) prop);
            JsonArray intArrayPropJson = new JsonArray();
            nodeJson.add(jsonName, intArrayPropJson);
            for (int intProp : intArray) {
                intArrayPropJson.add(intProp);
            }
        } else if (prop != null) {
            nodeJson.addProperty(jsonName, prop.toString());
            String message = "Node " + node.getClass().getSimpleName() + " contains unknown type prop: "
                    + jsonName + " of type " + prop.getClass();
            logger.error(message);
        }
    }
    return nodeJson;
}