【发布时间】:2015-09-03 01:24:39
【问题描述】:
我正在尝试使用自定义转换器进行改造
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(BuildConfig.BASE_SERVER_ENDPOINT)
.setClient(new OkClient(client)).setConverter(new CitationResponseConverter())
.setLogLevel(RestAdapter.LogLevel.FULL);
下面是我的自定义转换器
public class CitationResponseConverter implements Converter {
@Override
public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
try {
InputStream in = typedInput.in(); // convert the typedInput to String
String string = fromStream(in);
in.close(); // we are responsible to close the InputStream after use
if (String.class.equals(type)) {
return string;
} else {
return new Gson().fromJson(string,
type); // convert to the supplied type, typically Object, JsonObject or Map<String, Object>
}
} catch (Exception e) { // a lot may happen here, whatever happens
throw new ConversionException(
e); // wrap it into ConversionException so retrofit can process it
}
}
@Override
public TypedOutput toBody(Object object) {
return null;
}
private static String fromStream(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
out.append("\r\n");
}
return out.toString();
}
}
我收到以下错误
retrofit.RetrofitError: method POST must have a request body.
在尝试进行此 api 调用时
@POST("/service/citations")
Observable<CitationMain> getCitations(@Body CitationRequestBody body);
我认为转换器正在覆盖对 api 调用的请求,我该如何避免这种情况并传递改造服务中定义的请求正文。
回应:
{
"citations": [
{
"coverdatestart": "2015-05-01",
"coverimage": [
"09699961/S0969996115X00040/cov200h.gif",
"09699961/S0969996115X00040/cov150h.gif"
],
"pubyear": "2015",
"refimage": [
"09699961/S0969996115X00040/S0969996115000522/gr1-t.gif",
"09699961/S0969996115X00040/S0969996115000522/gr1.jpg"
],
"volissue": "Volume 77",
"volume": "77"
},
{
"pubdatetxt": "19700101",
"refimage": "mma:otto_4_9781455748600/9781455748600_0020",
}
]
}
【问题讨论】:
-
是的,
toBody就是这样做的。你需要在那里实际返回一些东西,否则你的身体里什么都没有。例如,您可以尝试让您的自定义转换器扩展 GsonConverter。 -
但是对于你想要做的事情(接收 jsonobjects 或纯字符串),我会使用标准的 GsonConverter,对于纯字符串服务,返回一个
Observable<Response>,我会映射到从响应中获取字符串的方法(使用reponse.getBody().in()上的 fromStream 方法) -
酷,我会试试的。我正在尝试使用自定义转换器作为其中一个 api 返回 json 字段作为 String 或 List
取决于大小。 -
不确定我是否理解您的评论,如果只有一个值,是否类似于
{"field": "value"}和{"field": ["value1", "value2"]}?在这种情况下,你不能有一个模型对象来处理这两个问题,除非你以某种方式将"value"转换为["value"]。 -
可以发几个回复的例子,以及
CitationMain的相关内容吗?
标签: android json parsing gson retrofit