Skip to content

Java 8 Optional not working with @JsonUnwrapped on unwrappable type #2565

@yushijinhun

Description

@yushijinhun
public static class Bean {
	public @JsonUnwrapped Optional<String> value;
}

var b = new Bean();
b.value = Optional.of("str");
jackson.writeValueAsString(b);
com.fasterxml.jackson.core.JsonGenerationException: Can not write a string, expecting field name (context: Object)
	at [email protected]/com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:2080)
	at [email protected]/com.fasterxml.jackson.core.json.JsonGeneratorImpl._reportCantWriteValueExpectName(JsonGeneratorImpl.java:248)
	at [email protected]/com.fasterxml.jackson.core.json.JsonGeneratorImpl._verifyPrettyValueWrite(JsonGeneratorImpl.java:238)
	at [email protected]/com.fasterxml.jackson.core.json.WriterBasedJsonGenerator._verifyValueWrite(WriterBasedJsonGenerator.java:894)
	at [email protected]/com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeString(WriterBasedJsonGenerator.java:400)
	at [email protected]/com.fasterxml.jackson.databind.ser.std.StringSerializer.serialize(StringSerializer.java:41)
	at [email protected]/com.fasterxml.jackson.databind.ser.std.ReferenceTypeSerializer.serialize(ReferenceTypeSerializer.java:381)
	at [email protected]/com.fasterxml.jackson.databind.ser.impl.UnwrappingBeanPropertyWriter.serializeAsField(UnwrappingBeanPropertyWriter.java:127)
	at [email protected]/com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:722)
	at [email protected]/com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:166)
	at [email protected]/com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
	at [email protected]/com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
	at [email protected]/com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:4094)
	at [email protected]/com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3404)

I think change the expression to

_unwrapper != null && _valueSerializer.isUnwrappingSerializer()

may fix it, but _valueSerializer can be null here. Hoping anyone familiar with this can fix it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions