How can I return String or JSONObject from asynchronous callback using Retrofit?

后端 未结 7 1820
无人及你
无人及你 2020-11-30 00:34

For example, calling

api.getUserName(userId, new Callback() {...});

cause:

retrofit.RetrofitError: retrofit.         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-30 00:51

    When @lordmegamax answer completely work there is much nicer solution which is come from

    Okio is a new library that complements java.io and java.nio

    other squares project which already tight with retrofit and therefore you don't need to add any new dependency and it's have to be reliable:

    ByteString.read(body.in(), (int) body.length()).utf8();
    

    ByteString is an immutable sequence of bytes. For character data, String is fundamental. ByteString is String's long-lost brother, making it easy to treat binary data as a value. This class is ergonomic: it knows how to encode and decode itself as hex, base64, and UTF-8.

    Full example:

    public class StringConverter implements Converter {
      @Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
        try {
          return ByteString.read(body.in(), (int) body.length()).utf8();
        } catch (IOException e) {
          throw new ConversionException("Problem when convert string", e);
        }
      }
    
      @Override public TypedOutput toBody(Object object) {
        return new TypedString((String) object);
      }
    }
    

提交回复
热议问题