Java Code Examples for com.fasterxml.jackson.core.JsonGenerator#writeBoolean()

The following examples show how to use com.fasterxml.jackson.core.JsonGenerator#writeBoolean() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BooleanFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public final void serializeAsField(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception
{
    if (broken) {
        fallbackWriter.serializeAsField(bean, gen, prov);
        return;
    }
    boolean value;
    try {
        value = _propertyAccessor.booleanField(bean, _propertyIndex);
    } catch (Throwable t) {
        _handleProblem(bean, gen, prov, t, false);
        return;
    }
    if (!_suppressableSet || _suppressableBoolean != value) {
        gen.writeFieldName(_fastName);
        gen.writeBoolean(value);
    }
}
 
Example 2
Source File: BooleanFieldPropertyWriter.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public final void serializeAsElement(Object bean, JsonGenerator gen, SerializerProvider prov) throws Exception
{
    if (broken) {
        fallbackWriter.serializeAsElement(bean, gen, prov);
        return;
    }
    boolean value;
    try {
        value = _propertyAccessor.booleanField(bean, _propertyIndex);
    } catch (Throwable t) {
        _handleProblem(bean, gen, prov, t, true);
        return;
    }
    if (!_suppressableSet || _suppressableBoolean != value) {
        gen.writeBoolean(value);
    } else { // important: MUST output a placeholder
        serializeAsPlaceholder(bean, gen, prov);
    }
}
 
Example 3
Source File: Jackson.java    From ts-reaktive with MIT License 6 votes vote down vote up
public static void writeTo(JsonGenerator gen, JSONEvent evt) throws IOException {
    if (evt == JSONEvent.START_OBJECT) {
        gen.writeStartObject();
    } else if (evt == JSONEvent.END_OBJECT) {
        gen.writeEndObject();
    } else if (evt == JSONEvent.START_ARRAY) {
        gen.writeStartArray();
    } else if (evt == JSONEvent.END_ARRAY) {
        gen.writeEndArray();
    } else if (evt == JSONEvent.TRUE) {
        gen.writeBoolean(true);
    } else if (evt == JSONEvent.FALSE) {
        gen.writeBoolean(false);
    } else if (evt == JSONEvent.NULL) {
        gen.writeNull();
    } else if (evt instanceof JSONEvent.FieldName) {
        gen.writeFieldName(JSONEvent.FieldName.class.cast(evt).getName());
    } else if (evt instanceof JSONEvent.StringValue) {
        gen.writeString(JSONEvent.StringValue.class.cast(evt).getValueAsString());
    } else if (evt instanceof JSONEvent.NumericValue) {
        gen.writeNumber(JSONEvent.NumericValue.class.cast(evt).getValueAsString());
    }
}
 
Example 4
Source File: AvroObjectSerializer.java    From stream-registry with Apache License 2.0 6 votes vote down vote up
private void serialize(Object value, JsonGenerator g) throws IOException {
  if (value instanceof AvroObject) {
    serializeObject((AvroObject) value, g);
  } else if (value instanceof AvroArray) {
    serializeArray((AvroArray) value, g);
  } else if (value instanceof String) {
    g.writeString((String) value);
  } else if (value instanceof Double) {
    g.writeNumber((double) value);
  } else if (value instanceof Float) {
    g.writeNumber((float) value);
  } else if (value instanceof Long) {
    g.writeNumber((long) value);
  } else if (value instanceof Integer) {
    g.writeNumber((int) value);
  } else if (value instanceof Boolean) {
    g.writeBoolean((boolean) value);
  } else if (value == null) {
    g.writeNull();
  } else {
    throw new IllegalStateException("Unexpected value " + value.getClass() + ": " + value);
  }
}
 
Example 5
Source File: JsonTerminologyIO.java    From termsuite-core with Apache License 2.0 6 votes vote down vote up
private static <P extends Enum<P> & Property<?>> void writePropertyValue(JsonGenerator jg, P p, Object value) throws IOException {
	if(p.getRange().equals(Double.class)) 
		jg.writeNumber((Double)value);
	else if(p.getRange().equals(Integer.class)) 
		jg.writeNumber((Integer)value);
	else if(p.getRange().equals(Float.class)) 
		jg.writeNumber((Float)value);
	else if(p.getRange().equals(String.class)) 
		jg.writeString((String)value);
	else if(p.getRange().equals(Boolean.class)) 
		jg.writeBoolean((Boolean)value);
	else if(PropertyValue.class.isAssignableFrom(p.getRange())) {
		jg.writeString(((PropertyValue)value).getSerializedString());
	} else if(Collection.class.isAssignableFrom(p.getRange())) {
		jg.writeStartArray();
		for(Object o:(Collection<?>)value)
			jg.writeObject(o);
		jg.writeEndArray();
	} else
		
		throw new UnsupportedOperationException(String.format("Cannot serialize property %s. Unsupported range: %s", p, p.getRange()));
}
 
Example 6
Source File: TransactionInfoCallStackSerializer.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(TransactionInfoViewModel.CallStack value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartArray();
    jgen.writeString(value.getDepth());
    jgen.writeNumber(value.getBegin());
    jgen.writeNumber(value.getEnd());
    jgen.writeBoolean(value.isExcludeFromTimeline());
    jgen.writeString(value.getApplicationName());
    jgen.writeNumber(value.getTab());
    jgen.writeString(value.getId());
    jgen.writeString(value.getParentId());
    jgen.writeBoolean(value.isMethod());
    jgen.writeBoolean(value.isHasChild());
    jgen.writeString(value.getTitle());
    jgen.writeString(value.getArguments());
    jgen.writeString(value.getExecuteTime());
    jgen.writeString(value.getGap());
    jgen.writeString(value.getElapsedTime());
    jgen.writeString(value.getBarWidth());
    jgen.writeString(value.getExecutionMilliseconds());
    jgen.writeString(value.getSimpleClassName());
    jgen.writeString(value.getMethodType());
    jgen.writeString(value.getApiType());
    jgen.writeString(value.getAgent());
    jgen.writeBoolean(value.isFocused());
    jgen.writeBoolean(value.isHasException());
    jgen.writeBoolean(value.isAuthorized());
    jgen.writeEndArray();
}
 
Example 7
Source File: RemoveStopWords.java    From algoliasearch-client-java-2 with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void serialize(RemoveStopWords value, JsonGenerator gen, SerializerProvider serializers)
    throws IOException {
  if (value instanceof RemoveStopWordsBoolean) {
    gen.writeBoolean((Boolean) value.getInsideValue());
  } else if (value instanceof RemoveStopWordsListString) {
    List<String> list = (List<String>) value.getInsideValue();
    gen.writeObject(list);
  }
}
 
Example 8
Source File: JsonWriterUtil.java    From odata with Apache License 2.0 5 votes vote down vote up
/**
 * Write the given primitive value to the JSON stream by using the given JSON generator.
 *
 * @param primitiveValue The given primitive value to write.
 * @param jsonGenerator  The given JSON generator.
 * @throws IOException If unable to write to the json output stream
 */
public static void writePrimitiveValue(Object primitiveValue, JsonGenerator jsonGenerator) throws IOException {

    Class<?> primitiveClass = PrimitiveUtil.wrap(primitiveValue.getClass());
    if (String.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeString(String.valueOf(primitiveValue));
    } else if (Byte.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeObject(primitiveValue);
    } else if (Short.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((short) primitiveValue);
    } else if (Integer.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((int) primitiveValue);
    } else if (Float.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((float) primitiveValue);
    } else if (Double.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((double) primitiveValue);
    } else if (Long.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((long) primitiveValue);
    } else if (Boolean.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeBoolean((boolean) primitiveValue);
    } else if (UUID.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeString(primitiveValue.toString());
    } else if (BigDecimal.class.isAssignableFrom(primitiveClass)) {
        jsonGenerator.writeNumber((BigDecimal) primitiveValue);
    } else {
        jsonGenerator.writeObject(primitiveValue.toString());
    }
}
 
Example 9
Source File: BooleanSerializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final void serializeWithType(Object value, JsonGenerator g, SerializerProvider provider,
        TypeSerializer typeSer) throws IOException
{
    // 27-Mar-2017, tatu: Actually here we CAN NOT serialize as number without type,
    //    since with natural types that would map to number, not boolean. So choice
    //    comes to between either add type id, or serialize as boolean. Choose
    //    latter at this point
    g.writeBoolean(Boolean.TRUE.equals(value));
}
 
Example 10
Source File: BooleanJsonSerializer.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(Object value, JsonGenerator generator, SerializerProvider serializers) throws IOException {

	int boolean1 = Integer.valueOf((String.valueOf(value)));
	boolean newValue = false;
	if (boolean1 == 1)
		newValue = true;
	generator.writeBoolean(newValue);

}
 
Example 11
Source File: SyncingJsonSerializer.java    From etherjar with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(SyncingJson value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    if (value == null) {
        gen.writeNull();
    } else if (value.isSyncing()) {
        gen.writeStartObject();
        writeField(gen, "startingBlock", value.getStartingBlock());
        writeField(gen, "currentBlock", value.getCurrentBlock());
        writeField(gen, "highestBlock", value.getHighestBlock());
        gen.writeEndObject();
    } else {
        gen.writeBoolean(false);
    }
}
 
Example 12
Source File: JacksonAutoConfiguration.java    From open-cloud with MIT License 4 votes vote down vote up
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
    jgen.writeBoolean(false);
}
 
Example 13
Source File: RangeBoundValueSerializer.java    From presto with Apache License 2.0 4 votes vote down vote up
private void writeValue(Object obj, JsonGenerator gen)
        throws IOException
{
    if (obj == null) {
        throw new IllegalStateException("Unexpected null value");
    }
    else if (obj instanceof String) {
        gen.writeString((String) obj);
    }
    else if (Number.class.isAssignableFrom(obj.getClass())) {
        if (obj instanceof Long) {
            gen.writeNumber((Long) obj);
        }
        else if (obj instanceof Integer) {
            gen.writeNumber((Integer) obj);
        }
        else if (obj instanceof Short) {
            gen.writeNumber((Short) obj);
        }
        else if (obj instanceof Double) {
            gen.writeNumber((Double) obj);
        }
        else if (obj instanceof Float) {
            gen.writeNumber((Float) obj);
        }
        else if (obj instanceof BigInteger) {
            gen.writeNumber((BigInteger) obj);
        }
        else if (obj instanceof BigDecimal) {
            gen.writeNumber((BigDecimal) obj);
        }
        else {
            throw new IllegalStateException("Unknown number value: " + obj);
        }
    }
    else if (obj instanceof Boolean) {
        gen.writeBoolean((Boolean) obj);
    }
    else if (obj instanceof byte[]) {
        gen.writeBinary((byte[]) obj);
    }
}
 
Example 14
Source File: ProtobufSerializer.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
protected void writeValue(
        FieldDescriptor field,
        Object value,
        JsonGenerator generator,
        SerializerProvider serializerProvider
) throws IOException {
  switch (field.getJavaType()) {
    case INT:
      generator.writeNumber((Integer) value);
      break;
    case LONG:
      generator.writeNumber((Long) value);
      break;
    case FLOAT:
      generator.writeNumber((Float) value);
      break;
    case DOUBLE:
      generator.writeNumber((Double) value);
      break;
    case BOOLEAN:
      generator.writeBoolean((Boolean) value);
      break;
    case STRING:
      generator.writeString((String) value);
      break;
    case ENUM:
      EnumValueDescriptor enumDescriptor = (EnumValueDescriptor) value;

      // special-case NullValue
      if (NULL_VALUE_FULL_NAME.equals(enumDescriptor.getType().getFullName())) {
        generator.writeNull();
      } else if (writeEnumsUsingIndex(serializerProvider)) {
        generator.writeNumber(enumDescriptor.getNumber());
      } else {
        generator.writeString(enumDescriptor.getName());
      }
      break;
    case BYTE_STRING:
      generator.writeString(serializerProvider.getConfig().getBase64Variant().encode(((ByteString) value).toByteArray()));
      break;
    case MESSAGE:
      Class<?> subType = value.getClass();

      JsonSerializer<Object> serializer = serializerCache.get(subType);
      if (serializer == null) {
        serializer = serializerProvider.findValueSerializer(value.getClass(), null);
        serializerCache.put(subType, serializer);
      }

      serializer.serialize(value, generator, serializerProvider);
      break;
    default:
      throw unrecognizedType(field, generator);
  }
}
 
Example 15
Source File: JsonDeltaSerializerWithNavigations.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
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);
  } 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.JSON_MEDIA_ETAG, stream.getMediaETag());
        }
        if (stream.getType() != null) {
          json.writeStringField(name + Constants.JSON_MEDIA_CONTENT_TYPE, stream.getType());
        }
      }
      if (isODataMetadataFull) {
        if (stream.getRel() != null && stream.getRel().equals(Constants.NS_MEDIA_READ_LINK_REL)) {
          json.writeStringField(name + Constants.JSON_MEDIA_READ_LINK, stream.getHref());
        }
        if (stream.getRel() == null || stream.getRel().equals(Constants.NS_MEDIA_EDIT_LINK_REL)) {
          json.writeStringField(name + Constants.JSON_MEDIA_EDIT_LINK, stream.getHref());
        }
      }
    }
  } else {
    json.writeString(value);
  }
}
 
Example 16
Source File: ODataJsonSerializer.java    From olingo-odata4 with Apache License 2.0 4 votes vote down vote up
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);
  } 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);
  }
}
 
Example 17
Source File: BooleanSerializer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public void serialize(Object value, JsonGenerator g, SerializerProvider provider) throws IOException {
    g.writeBoolean(Boolean.TRUE.equals(value));
}
 
Example 18
Source File: SerializeSupport.java    From curiostack with MIT License 4 votes vote down vote up
public static void printBool(boolean value, JsonGenerator gen) throws IOException {
  gen.writeBoolean(value);
}
 
Example 19
Source File: ErrorAndToStringUnknownTypeSerializer.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public void serializeFromError(JsonStreamContext ctxt, @Nullable Exception error, Object value, JsonGenerator jgen, SerializerProvider configurableSerializerProvider) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Recovering from json serialization error, serializing "+value+": "+error);

    if (BidiSerialization.isStrictSerialization())
        throw new JsonMappingException("Cannot serialize "
            + (ctxt!=null && !ctxt.inRoot() ? "object containing " : "")
            + value.getClass().getName()+" when strict serialization requested");

    if (WARNED_CLASSES.add(value.getClass().getCanonicalName())) {
        log.warn("Standard serialization not possible for "+value.getClass()+" ("+value+")", error);
    }
    JsonStreamContext newCtxt = jgen.getOutputContext();

    // very odd, but flush seems necessary when working with large objects; presumably a buffer which is allowed to clear itself?
    // without this, when serializing the large (1.5M) Server json object from BrooklynJacksonSerializerTest creates invalid json,
    // containing:  "foo":false,"{"error":true,...
    jgen.flush();

    boolean createObject = !newCtxt.inObject() || newCtxt.getCurrentName()!=null;
    if (createObject) {
        jgen.writeStartObject();
    }

    if (allowEmpty(value.getClass())) {
        // write nothing
    } else {

        jgen.writeFieldName("error");
        jgen.writeBoolean(true);

        jgen.writeFieldName("errorType");
        jgen.writeString(NotSerializableException.class.getCanonicalName());

        jgen.writeFieldName("type");
        jgen.writeString(value.getClass().getCanonicalName());

        jgen.writeFieldName("toString");
        jgen.writeString(value.toString());

        if (error!=null) {
            jgen.writeFieldName("causedByError");
            jgen.writeString(error.toString());
        }

    }

    if (createObject) {
        jgen.writeEndObject();
    }

    while (newCtxt!=null && !newCtxt.equals(ctxt)) {
        if (jgen.getOutputContext().inArray()) { jgen.writeEndArray(); continue; }
        if (jgen.getOutputContext().inObject()) { jgen.writeEndObject(); continue; }
        break;
    }

}
 
Example 20
Source File: GeoTimeSerieSerializer.java    From warp10-platform with Apache License 2.0 4 votes vote down vote up
@Override
public void serialize(GeoTimeSerie gts, JsonGenerator gen, SerializerProvider provider) throws IOException {
  Metadata metadata = gts.getMetadata();

  gen.writeStartObject();
  MetadataSerializer.serializeMetadataFields(metadata, gen);
  gen.writeFieldName(FIELD_VALUES);
  gen.writeStartArray(gts.size());

  for (int i = 0; i < gts.size(); i++) {
    long ts = GTSHelper.tickAtIndex(gts, i);
    long location = GTSHelper.locationAtIndex(gts, i);
    long elevation = GTSHelper.elevationAtIndex(gts, i);
    Object v = GTSHelper.valueAtIndex(gts, i);

    gen.writeStartArray();
    gen.writeNumber(ts);
    if (GeoTimeSerie.NO_LOCATION != location) {
      double[] latlon = GeoXPLib.fromGeoXPPoint(location);
      gen.writeNumber(latlon[0]);
      gen.writeNumber(latlon[1]);
    }
    if (GeoTimeSerie.NO_ELEVATION != elevation) {
      gen.writeNumber(elevation);
    }

    // Do not use directly gen.writeObject() because it is VERY slow.
    switch (gts.getType()) {
      case UNDEFINED:
        gen.writeObject(v);
        break;
      case LONG:
        gen.writeNumber((long) v);
        break;
      case DOUBLE:
        gen.writeNumber((double) v);
        break;
      case BOOLEAN:
        gen.writeBoolean((boolean) v);
        break;
      case STRING:
        gen.writeString((String) v);
        break;
    }
    gen.writeEndArray();
  }
  gen.writeEndArray();

  gen.writeEndObject();
}