Optional request body - optional type is not recorgnized

Hi guys,

I came across an optional request for a ServiceCall and it appears to me that the check for optional type does fail in JacksonSerializerFactory.

          if (bytes.isEmpty() && this.type == Optional.class) {
            bytes = ByteString.fromString("null");
          return reader.readValue(bytes.iterator().asInputStream());

It seems to me that my optional is wrapped under different type implementation:

Would anybody advice what would be the proper way to use optional for request, or is this the expected behavior?


Hi @ktulinger,

I didn’t understand how are you using Optional. Can you give more information about the context that you are trying to use that ? like the signature of service call or something.


    ServiceCall<Optional<RequestImpl>, ResponseImpl> query(
            String identifierType,
            String identifier,
            Optional<Integer> size,
            Optional<String> sortKey,
            Optional<Double> score
    ) { ... }

where RequestImpl is defined as

@Value.Style(additionalJsonAnnotations = {JsonNaming.class}, forceJacksonPropertyNames = false, jdkOnly = true)
@JsonSerialize(as = ImmutableRequestImpl.class)
@JsonDeserialize(as = ImmutableRequestImpl.class)
public interface RequestImpl extends Jsonable {
    Optional<Integer> size();

    Optional<String> sortKey();

    Optional<Double> score();

Ok, as far as I know seems like you request body does not need to be Optional.

If this is a GET request, avoid body and pass this params through the URL as query params
If this is a POST or PUT request I strongly recommend to not use an entire optional body, yes you can have some propeties that are Optional but if the request body is None what kind of data alteration is that request causing ?

The joke is here that the request is POST and it mixes parameters from query and post body, so the post body can be completely empty (thus I’m using optional). I’m not able to change this mechanism right away eventhough it’s breaking the “web” principles.

Back to the original question, when the optional is wrapped (I didn’t do anything special with it, so it feels like normal usage) as I posted on the screenshot, it is not recognized as optional and the condition above the screenshot does not trigger - is this an expected behaviour for an optional request?

You do not need to specify the request as optional like you did

ServiceCall<Optional< RequestImp l>>

just write

ServiceCall< RequestImpl >

If the others parameters like size, score and sortkey does not exists in the request body they ill be empty in the RequestImpl model. As far as I know the body of an service call must be parseble to json so check if there are any implicit parser for Optional to.