spi*_*ce7 5 java android gson retrofit
我正在使用Gson解析Android上服务器的响应.每个响应都有一些无用的(对我而言)数据,这使我的Gson模型变得复杂.这是json返回的一般层次结构:
response: {
date: 1406253006807,
otherUselessData1: "This is some useless data",
otherUselessData2: "This is some useless data",
usefulJsonObject: { <---- This is really the object that I care about
}
}
Run Code Online (Sandbox Code Playgroud)
usefulJsonObject我所能做到的一切都高于或者处于同一水平.为每个请求返回无用的数据,并将实际响应嵌入到下面作为usefulJsonObject.这不是一个大问题,但它真的让我的gson模型对象变得混乱.
例如: 比方说,我有3个请求,我可以做:A,B和C.对于每个响应,我似乎需要至少制作3个自定义类.
public class ResponseA {
@SerializedName("response") ResponseObjectA responseObject;
public static class ResponseObjectA {
@SerializedName("usefulJsonObject") UsefulObjectA usefulObject;
}
public static class UsefulObjectA {
}
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一些解决方案,但我没有找到任何优雅的东西,不会给我的过程增加额外的一步.我正在使用改造来做我的http请求,它真的很好,它只是将完全解析的gson对象返回给我.我想到了其他解决方案,比如让有用的对象只是一个JsonElement,然后在第一次回来之后进行第二次gson调用.再次,不理想.
我只是想知道我是否遗漏了什么.当然,我不是唯一一个遇到类似事情的人,所以我想我会问其他人如何处理这样的事情.
我从来没有找到一种优雅的方式来处理 Gson。我尝试了几种泛型选项,但所有这些都不起作用或有一些不足之处。
由于我使用的是 Retrofit,因此我决定重写 GsonConverter,并从所有请求中过滤掉不必要的信息。它最终变得不那么灵活,就像我不能使用相同的 Retrofit 网络接口来调用其他服务器一样,但我并没有真正这样做,而且它也有 2 轮 json 解析调用的缺点(嗯)。您可能可以更有效地完成此操作,但这目前对我有用。
public class CustomGsonConverter extends GsonConverter {
private Gson mGson;
public CustomGsonConverter(Gson gson) {
super(gson);
this.mGson = gson;
}
public CustomGsonConverter(Gson gson, String encoding) {
super(gson, encoding);
this.mGson = gson;
}
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException {
try {
CustomResponse customResponse = mGson.fromJson(new InputStreamReader(body.in()), CustomResponse.class);
return mGson.fromJson(customResponse.responseObject.data, type);
} catch (IOException e) {
throw new ConversionException(e);
}
}
public static class CustomResponse {
@SerializedName("rsp") ResponseObject responseObject;
public static class ResponseObject {
// @SerializedName("date") long date;
@SerializedName("data") JsonElement data;
}
}
}
Run Code Online (Sandbox Code Playgroud)
也许有更好的方法,只是我没有意识到。
| 归档时间: |
|
| 查看次数: |
2812 次 |
| 最近记录: |