【发布时间】:2015-09-27 19:36:32
【问题描述】:
我有以下类层次结构
public abstract class SyncModel {
@Expose
@SerializedName("id")
private Long globalId;
@Expose
protected DateTime lastModified;
/* Constructor, methods... */
}
public class Event extends SyncModel {
@Expose
private String title;
/* Other fields, constructor, methods... */
}
我需要向后端发送一个 Event 实例。
案例1.@Body
当我在请求正文中发布 Event 实例时,它被很好地序列化了。
RetroFit Java 接口:
public interface EventAPI {
@POST("/event/create")
void sendEvent(@Body Event event, Callback<Long> cbEventId);
}
RetroFit 日志:
D 改造 ---> HTTP POST http://hostname:8080/event/create D 改造Content-Type:application/json;字符集=UTF-8 D 改造内容长度:297 D 改造 {"title":"Test Event 01",...,"id":null,"lastModified":"2015-07-09T14:17:08.860+03:00"} D 改造 ---> END HTTP(297 字节正文)案例2。@Field
但是当我在请求参数中发布 Event 实例时,只有抽象类被序列化。
RetroFit Java 接口:
@FormUrlEncoded
@POST("/event/create")
void sendEvent(@Field("event") Event event, Callback<Long> cbEventId);
RetroFit 日志:
D 改造 ---> HTTP POST http://hostname:8080/event/create D Retrofit Content-Type:application/x-www-form-urlencoded;字符集=UTF-8 D 改造内容长度:101 D 改造 event=SyncModel%28globalId%3Dnull%2C+lastModified%3D2015-07-09T13%3A36%3A33.510%2B03%3A00%29 D 改造 ---> END HTTP(101 字节正文)注意区别。
问题
为什么?
如何在请求参数中将序列化的 Event 实例发送到后端?
我是否需要为抽象类编写自定义 JSON 序列化程序? (例如:Polymorphism with JSON)
还是它是 RetroFit 特有的功能(忽略子类)?
我还注意到,在第二种情况下,globalId 字段序列化名称是 globalId,但它应该是 id!这让我觉得 RetroFit 对 @Field 使用不同的 GsonConverter 而不是 @Body 参数...
配置
Gradle 依赖项
compile 'com.squareup.retrofit:retrofit:1.9.+'
compile 'com.squareup.okhttp:okhttp:2.3.+'
compile 'net.danlew:android.joda:2.8.+'
compile ('com.fatboyindustrial.gson-jodatime-serialisers:gson-jodatime-serialisers:1.1.0') { // GSON + Joda DateTime
exclude group: 'joda-time', module: 'joda-time'
}
REST 客户端
public final class RESTClient {
// Not a real server URL
public static final String SERVER_URL = "http://hostname:8080";
// one-time initialization
private static GsonBuilder builder = new GsonBuilder()
.serializeNulls()
.excludeFieldsWithoutExposeAnnotation()
.setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'");
// Joda DateTime type support
private static Gson gson = Converters.registerDateTime(builder).create();
private static RestAdapter restAdapter = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL) // for development
.setEndpoint(SERVER_URL)
.setConverter(new GsonConverter(gson)) // custom converter
.build();
private static final EventAPI eventService = restAdapter.create(EventAPI.class);
/* + Getter for eventService */
static {
// forget them
restAdapter = null;
gson = null;
builder = null;
}
}
打电话
RESTClient.getEventService().sendEvent(event, new Callback<Long>() {/* ... */});
【问题讨论】:
标签: android gson abstract-class retrofit