Example usage for com.fasterxml.jackson.core JsonGenerator writeNull

List of usage examples for com.fasterxml.jackson.core JsonGenerator writeNull

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator writeNull.

Prototype

public abstract void writeNull() throws IOException, JsonGenerationException;

Source Link

Document

Method for outputting literal Json null value.

Usage

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

protected void writeExpandedNavigationProperty(final ServiceMetadata metadata,
        final EdmNavigationProperty property, final Link navigationLink, final ExpandOption innerExpand,
        Integer toDepth, final SelectOption innerSelect, final CountOption innerCount,
        final boolean writeOnlyCount, final boolean writeOnlyRef, final Set<String> ancestors, String name,
        final JsonGenerator json) throws IOException, SerializerException, DecoderException {

    if (property.isCollection()) {
        if (writeOnlyCount) {
            if (navigationLink == null || navigationLink.getInlineEntitySet() == null) {
                writeInlineCount(property.getName(), 0, json);
            } else {
                writeInlineCount(property.getName(), navigationLink.getInlineEntitySet().getCount(), json);
            }/*from ww  w .j  a va 2  s  .co  m*/
        } else {
            if (navigationLink == null || navigationLink.getInlineEntitySet() == null) {
                if (innerCount != null && innerCount.getValue()) {
                    writeInlineCount(property.getName(), 0, json);
                }
                json.writeFieldName(property.getName());
                json.writeStartArray();
                json.writeEndArray();
            } else {
                if (innerCount != null && innerCount.getValue()) {
                    writeInlineCount(property.getName(), navigationLink.getInlineEntitySet().getCount(), json);
                }
                json.writeFieldName(property.getName());
                writeEntitySet(metadata, property.getType(), navigationLink.getInlineEntitySet(), innerExpand,
                        toDepth, innerSelect, writeOnlyRef, ancestors, name, json);
            }
        }
    } else {
        json.writeFieldName(property.getName());
        if (navigationLink == null || navigationLink.getInlineEntity() == null) {
            json.writeNull();
        } else {
            writeEntity(metadata, property.getType(), navigationLink.getInlineEntity(), null, innerExpand,
                    toDepth, innerSelect, writeOnlyRef, ancestors, name, json);
        }
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

protected void writeProperty(final ServiceMetadata metadata, final EdmProperty edmProperty,
        final Property property, final Set<List<String>> selectedPaths, final JsonGenerator json,
        Set<List<String>> expandedPaths, Linked linked, ExpandOption expand)
        throws IOException, SerializerException {
    boolean isStreamProperty = isStreamProperty(edmProperty);
    writePropertyType(edmProperty, json);
    if (!isStreamProperty) {
        json.writeFieldName(edmProperty.getName());
    }//  w w  w .j a va  2 s .  c om
    if (property == null || property.isNull()) {
        if (edmProperty.isNullable() == Boolean.FALSE && !isStreamProperty) {
            throw new SerializerException("Non-nullable property not present!",
                    SerializerException.MessageKeys.MISSING_PROPERTY, edmProperty.getName());
        } else {
            if (!isStreamProperty) {
                if (edmProperty.isCollection()) {
                    json.writeStartArray();
                    json.writeEndArray();
                } else {
                    json.writeNull();
                }
            }
        }
    } else {
        writePropertyValue(metadata, edmProperty, property, selectedPaths, json, expandedPaths, linked, expand);
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

protected void writePrimitiveValue(final String name, final EdmPrimitiveType type, final Object primitiveValue,
        final Boolean isNullable, final Integer maxLength, final Integer precision, final Integer scale,
        final Boolean isUnicode, final JsonGenerator json) throws EdmPrimitiveTypeException, IOException {
    final String value = type.valueToString(primitiveValue, isNullable, maxLength, precision, scale, isUnicode);
    if (value == null) {
        json.writeNull();
    } else if (type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Boolean)) {
        json.writeBoolean(Boolean.parseBoolean(value));
    } else if (type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Byte)
            || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Double)
            || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Int16)
            || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Int32)
            || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.SByte)
            || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Single)
            || (type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Decimal)
                    || type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Int64))
                    && !isIEEE754Compatible) {
        json.writeNumber(value);/*w  w w  . j  a v  a 2 s  .c om*/
    } else if (type == EdmPrimitiveTypeFactory.getInstance(EdmPrimitiveTypeKind.Stream)) {
        if (primitiveValue instanceof Link) {
            Link stream = (Link) primitiveValue;
            if (!isODataMetadataNone) {
                if (stream.getMediaETag() != null) {
                    json.writeStringField(name + constants.getMediaEtag(), stream.getMediaETag());
                }
                if (stream.getType() != null) {
                    json.writeStringField(name + constants.getMediaContentType(), stream.getType());
                }
            }
            if (isODataMetadataFull) {
                if (stream.getRel() != null && stream.getRel().equals(Constants.NS_MEDIA_READ_LINK_REL)) {
                    json.writeStringField(name + constants.getMediaReadLink(), stream.getHref());
                }
                if (stream.getRel() == null || stream.getRel().equals(Constants.NS_MEDIA_EDIT_LINK_REL)) {
                    json.writeStringField(name + constants.getMediaEditLink(), stream.getHref());
                }
            }
        }
    } else {
        json.writeString(value);
    }
}

From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java

/** Writes a geospatial value following the GeoJSON specification defined in RFC 7946. */
protected void writeGeoValue(final String name, final EdmPrimitiveType type, final Geospatial geoValue,
        final Boolean isNullable, JsonGenerator json, SRID parentSrid)
        throws EdmPrimitiveTypeException, IOException, SerializerException {
    if (geoValue == null) {
        if (isNullable == null || isNullable) {
            json.writeNull();
        } else {//from  w w  w .  jav a2 s  .c o  m
            throw new EdmPrimitiveTypeException("The literal 'null' is not allowed.");
        }
    } else {
        if (!type.getDefaultType().isAssignableFrom(geoValue.getClass())) {
            throw new EdmPrimitiveTypeException("The value type " + geoValue.getClass() + " is not supported.");
        }
        json.writeStartObject();
        json.writeStringField(Constants.ATTR_TYPE, geoValueTypeToJsonName.get(geoValue.getGeoType()));
        json.writeFieldName(
                geoValue.getGeoType() == Geospatial.Type.GEOSPATIALCOLLECTION ? Constants.JSON_GEOMETRIES
                        : Constants.JSON_COORDINATES);
        json.writeStartArray();
        switch (geoValue.getGeoType()) {
        case POINT:
            writeGeoPoint(json, (Point) geoValue);
            break;
        case MULTIPOINT:
            writeGeoPoints(json, (MultiPoint) geoValue);
            break;
        case LINESTRING:
            writeGeoPoints(json, (LineString) geoValue);
            break;
        case MULTILINESTRING:
            for (final LineString lineString : (MultiLineString) geoValue) {
                json.writeStartArray();
                writeGeoPoints(json, lineString);
                json.writeEndArray();
            }
            break;
        case POLYGON:
            writeGeoPolygon(json, (Polygon) geoValue);
            break;
        case MULTIPOLYGON:
            for (final Polygon polygon : (MultiPolygon) geoValue) {
                json.writeStartArray();
                writeGeoPolygon(json, polygon);
                json.writeEndArray();
            }
            break;
        case GEOSPATIALCOLLECTION:
            for (final Geospatial element : (GeospatialCollection) geoValue) {
                writeGeoValue(name, EdmPrimitiveTypeFactory.getInstance(element.getEdmPrimitiveTypeKind()),
                        element, isNullable, json, geoValue.getSrid());
            }
            break;
        }
        json.writeEndArray();

        if (geoValue.getSrid() != null && geoValue.getSrid().isNotDefault()
                && (parentSrid == null || !parentSrid.equals(geoValue.getSrid()))) {
            srid(json, geoValue.getSrid());
        }
        json.writeEndObject();
    }
}

From source file:org.apache.syncope.core.misc.serialization.SyncTokenSerializer.java

@Override
public void serialize(final SyncToken source, final JsonGenerator jgen, final SerializerProvider sp)
        throws IOException {

    jgen.writeStartObject();//from w ww .  j  a  v  a2 s  .  c  o  m

    jgen.writeFieldName("value");

    if (source.getValue() == null) {
        jgen.writeNull();
    } else if (source.getValue() instanceof Boolean) {
        jgen.writeBoolean((Boolean) source.getValue());
    } else if (source.getValue() instanceof Double) {
        jgen.writeNumber((Double) source.getValue());
    } else if (source.getValue() instanceof Long) {
        jgen.writeNumber((Long) source.getValue());
    } else if (source.getValue() instanceof Integer) {
        jgen.writeNumber((Integer) source.getValue());
    } else if (source.getValue() instanceof byte[]) {
        jgen.writeString(Base64.encodeBase64String((byte[]) source.getValue()));
    } else {
        jgen.writeString(source.getValue().toString());
    }

    jgen.writeEndObject();
}

From source file:org.fao.geonet.domain.SettingToObjectSerializer.java

public static void writeSettingValue(Setting s, JsonGenerator jsonGenerator) throws IOException {
    try {/*from  w  ww . ja v  a2 s .c o  m*/
        if (StringUtils.isNotEmpty(s.getValue())) {
            if (s.getDataType() == SettingDataType.BOOLEAN) {
                jsonGenerator.writeBoolean(Boolean.parseBoolean(s.getValue()));
            } else if (s.getDataType() == SettingDataType.INT) {
                jsonGenerator.writeNumber(Integer.parseInt(s.getValue()));
            } else if (s.getDataType() == SettingDataType.JSON) {
                ObjectMapper mapper = new ObjectMapper();
                jsonGenerator.writeTree(mapper.readTree(s.getValue()));
            } else {
                jsonGenerator.writeString(s.getValue());
            }
        } else {
            jsonGenerator.writeNull();
        }
    } catch (Exception e) {
        jsonGenerator.writeNull();
        jsonGenerator.writeStringField("erroneousValue", s.getValue());
        jsonGenerator.writeStringField("error", e.getMessage());
    }
}

From source file:org.onebusaway.nextbus.impl.rest.jackson.CapitalizeSerializer.java

@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {
    if (value == null) {
        gen.writeNull();
    }/*ww w .jav a 2s .com*/
    gen.writeString(WordUtils.capitalizeFully(value));
}

From source file:org.talend.dataprep.schema.csv.CSVSerializer.java

/**
 * Write the line content.//from   www  .j a v  a  2s .  c  o  m
 *
 * @param reader the csv reader to use as data source.
 * @param metadata the dataset metadata to use to get the columns.
 * @param generator the json generator used to actually write the line content.
 * @param separator the csv separator to use.
 * @param limit The maximum number of lines in the exported content.
 * @throws IOException if an error occurs.
 */
private void writeLineContent(CSVReader reader, DataSetMetadata metadata, JsonGenerator generator,
        String separator, long limit) throws IOException {
    String[] line;
    int current = 0;

    while ((line = reader.readNext()) != null && withinLimit(limit, current)) {
        // skip empty lines
        if (line.length == 1 && (StringUtils.isEmpty(line[0]) || line[0].charAt(0) == '\u0000')) {
            continue;
        }

        List<ColumnMetadata> columns = metadata.getRowMetadata().getColumns();
        generator.writeStartObject();
        int columnsSize = columns.size();
        for (int i = 0; i < columnsSize; i++) {
            ColumnMetadata columnMetadata = columns.get(i);

            generator.writeFieldName(columnMetadata.getId());

            // deal with additional content (line.length > columns.size)
            if (i == columnsSize - 1 && line.length > columnsSize) {
                String additionalContent = getRemainingColumns(line, i, separator);
                generator.writeString(cleanCharacters(additionalContent));
            }
            // deal with fewer content (line.length < columns.size)
            else if (i < line.length && line[i] != null) {
                generator.writeString(cleanCharacters(line[i]));
            }
            // deal with null
            else {
                generator.writeNull();
            }
        }
        generator.writeEndObject();
        current++;
    }
}

From source file:org.talend.dataprep.schema.xls.serialization.XlsRunnable.java

private void serializeColumns(Workbook workbook, JsonGenerator generator, Sheet sheet,
        List<ColumnMetadata> columns) throws IOException {

    for (int i = 0, size = sheet.getLastRowNum(); i <= size; i++) {
        if (limit > 0 && i > limit) {
            break;
        }/*from w  w w  . j  ava 2 s.c  om*/
        // is header line?
        Row row = sheet.getRow(i);
        if (isHeaderLine(i, columns) || row == null) {
            continue;
        }

        generator.writeStartObject();
        for (ColumnMetadata columnMetadata : columns) {

            // do not write the values if this has been detected as an header
            if (i < columnMetadata.getHeaderSize()) {
                continue;
            }

            int colId = Integer.parseInt(columnMetadata.getId());
            String cellValue = getCellValueAsString(row.getCell(colId),
                    workbook.getCreationHelper().createFormulaEvaluator());
            LOG.trace("cellValue for {}/{}: {}", i, colId, cellValue);
            generator.writeFieldName(columnMetadata.getId());
            if (cellValue != null) {
                generator.writeString(cellValue);
            } else {
                generator.writeNull();
            }
        }
        generator.writeEndObject();
    }
}

From source file:org.talend.dataprep.schema.xls.serialization.XlsxStreamRunnable.java

/**
 * @see Runnable#run()/*from  www.j a  v a  2s  . com*/
 */
@Override
public void run() {
    try {
        JsonGenerator generator = jsonFactory.createGenerator(jsonOutput);
        Workbook workbook = StreamingReader.builder() //
                .bufferSize(4096) //
                .rowCacheSize(1) //
                .open(rawContent);
        try {
            Sheet sheet = StringUtils.isEmpty(metadata.getSheetName()) ? //
                    workbook.getSheetAt(0) : workbook.getSheet(metadata.getSheetName());
            generator.writeStartArray();
            for (Row row : sheet) {
                if (limit > 0 && row.getRowNum() > limit) {
                    break;
                }
                if (!XlsSerializer.isHeaderLine(row.getRowNum(), metadata.getRowMetadata().getColumns())) {
                    generator.writeStartObject();
                    // data quality Analyzer doesn't like to not have all columns even if we don't have any values
                    // so create so field with empty value otherwise we get exceptions
                    int i = 0;
                    for (ColumnMetadata columnMetadata : metadata.getRowMetadata().getColumns()) {
                        Cell cell = row.getCell(i);
                        String cellValue = cell == null ? null : cell.getStringCellValue(); // StringUtils.EMPTY
                        generator.writeFieldName(columnMetadata.getId());
                        if (cellValue != null) {
                            generator.writeString(cellValue);
                        } else {
                            generator.writeNull();
                        }
                        i++;
                    }
                    generator.writeEndObject();
                }
            }
            generator.writeEndArray();
            generator.flush();
        } finally {
            workbook.close();
        }
    } catch (Exception e) {
        // Consumer may very well interrupt consumption of stream (in case of limit(n) use for sampling).
        // This is not an issue as consumer is allowed to partially consumes results, it's up to the
        // consumer to ensure data it consumed is consistent.
        LOG.debug("Unable to continue serialization for {}. Skipping remaining content.", metadata.getId(), e);
    } finally {
        try {
            jsonOutput.close();
        } catch (IOException e) {
            LOG.error("Unable to close output", e);
        }
    }
}