Multiple converters with Retrofit 2

后端 未结 4 1035
萌比男神i
萌比男神i 2020-12-13 10:30

I have a HATEOAS (HAL) REST service and managed to talk to it with the code below (using halarious as a conversion engine) but when I try to merge the converters (stal

4条回答
  •  一个人的身影
    2020-12-13 10:53

    You need to return null from the Converter.Factory if the type does not match. Keep the Class around in a field to compare it against.

    @Override
    public Converter fromResponseBody(Type type, Annotation[] annotations) {
      if (!this.type.equals(type)) {
        return null;
      }
      return new HALResponseBodyConverter<>(gson);
    }
    

    This will allow multiple instances to be used because each only applies to its own type.

    That said, however, you can probably get away with only using a single converter and pulling the class from the Type that is passed in.

    @Override
    public Converter fromResponseBody(Type type, Annotation[] annotations) {
      if (!HALResponse.class.isAssignableFrom(type)) {
        return null;
      }
      // TODO create converter with `type` now that you know what it is...
    }
    

    You can look at the Wire converter in the repo which does this for a full example.

提交回复
热议问题