46

例如,调用

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

原因:

retrofit.RetrofitError: retrofit.converter.ConversionException:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 
Expected a string but was BEGIN_OBJECT at line 1 column 2

我想我必须禁用 gson 解析成 POJO,但不知道该怎么做。

4

6 回答 6

49

我想到了。这很尴尬,但它很简单......临时解决方案可能是这样的:

 public void success(Response response, Response ignored) {
            TypedInput body = response.getBody();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()));
                StringBuilder out = new StringBuilder();
                String newLine = System.getProperty("line.separator");
                String line;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                    out.append(newLine);
                }

                // Prints the correct String representation of body. 
                System.out.println(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

但是,如果您想直接获取 Callback更好的方法是使用Converter

public class Main {
public interface ApiService {
    @GET("/api/")
    public void getJson(Callback<String> callback);
}

public static void main(String[] args) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(new MockClient())
            .setConverter(new StringConverter())
            .setEndpoint("http://www.example.com").build();

    ApiService service = restAdapter.create(ApiService.class);
    service.getJson(new Callback<String>() {
        @Override
        public void success(String str, Response ignored) {
            // Prints the correct String representation of body.
            System.out.println(str);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            System.out.println("Failure, retrofitError" + retrofitError);
        }
    });
}

static class StringConverter implements Converter {

    @Override
    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
        String text = null;
        try {
            text = fromStream(typedInput.in());
        } catch (IOException ignored) {/*NOP*/ }

        return text;
    }

    @Override
    public TypedOutput toBody(Object o) {
        return null;
    }

    public static String fromStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);
        }
        return out.toString();
    }
}

public static class MockClient implements Client {
    @Override
    public Response execute(Request request) throws IOException {
        URI uri = URI.create(request.getUrl());
        String responseString = "";

        if (uri.getPath().equals("/api/")) {
            responseString = "{result:\"ok\"}";
        } else {
            responseString = "{result:\"error\"}";
        }

        return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST,
                new TypedByteArray("application/json", responseString.getBytes()));
    }
  }
}

如果您知道如何改进此代码 - 请随时写下它。

于 2014-04-02T18:36:55.320 回答
32

一个可能的解决方案是使用JsonElement类型Callback( Callback<JsonElement>)。在您的原始示例中:

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

在成功方法中,您可以将 转换JsonElement为 aString或 a JsonObject

JsonObject jsonObj = element.getAsJsonObject();
String strObj = element.toString();
于 2014-08-25T01:33:11.753 回答
30

Retrofit 2.0.0-beta3 增加了一个converter-scalars模块,提供了一个 Converter.Factory用于转换String的 8 种原始类型和 8 种盒装原始类型作为text/plain主体。在您的普通转换器之前安装它,以避免将这些简单的标量传递给例如 JSON 转换器。

因此,首先将converter-scalars模块添加到build.gradle您的应用程序的文件中。

dependencies {
    ...
    // use your Retrofit version (requires at minimum 2.0.0-beta3) instead of 2.0.0
    // also do not forget to add other Retrofit module you needed
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
}

然后,Retrofit像这样创建您的实例:

new Retrofit.Builder()
        .baseUrl(BASE_URL)
        // add the converter-scalars for coverting String
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()
        .create(Service.class);

现在您可以像这样使用 API 声明:

interface Service {

    @GET("/users/{id}/name")
    Call<String> userName(@Path("userId") String userId);

    // RxJava version
    @GET("/users/{id}/name")
    Observable<String> userName(@Path("userId") String userId);
}
于 2015-08-29T07:30:36.433 回答
21

答案可能比已经提到的要短得多,并且不需要任何额外的库:

在声明中使用Response如下:

... Callback<Response> callback);

在处理响应时:

@Override
public void success(Response s, Response response) {
    new JSONObject(new String(((TypedByteArray) response.getBody()).getBytes()))
}
于 2015-07-07T14:58:51.753 回答
4

当@lordmegamax 回答完全起作用时,会有更好的解决方案来自

Okio 是一个补充 java.io 和 java.nio 的新库

其他 squares 项目已经很紧密,retrofit因此您不需要添加任何新的依赖项,并且它必须是可靠的:

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

ByteString 是一个不可变的字节序列。对于字符数据,String 是基础。ByteString 是 String 失散多年的兄弟,可以很容易地将二进制数据视为一个值。这个类符合人体工程学:它知道如何将自己编码和解码为十六进制、base64 和 UTF-8。

完整示例:

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);
  }
}
于 2015-05-30T17:19:28.653 回答
-1

获取调用 JSONObject 或 JSONArray

您可以创建自定义工厂或从此处复制它:https ://github.com/marcinOz/Retrofit2JSONConverterFactory

于 2016-04-21T13:35:45.600 回答