2016-12-07 58 views
0

我有一個改造很奇怪的問題,實際上它可能是一個bug。 我想向服務器發送包含一些數據的POST請求。我的數據在Request類的子類中。序列化繼承與改進類

public abstract class Request {} 
public abstract class Measurement {} 

public class StepMeasurement extends Measurement { 
    ... 
    public int value; 
} 
public class SendStepsRequest extends Request { 
    public List<StepMeasurement> steps; 
} 

示例當然非常簡單。我已經準備了一個接口用於發送它:

public interface EndpointInterface { 

@Headers({"Content-Type: application/json"}) 
@POST("/patients/{id}/{dataType}") 
Call<ResponseBody> postRequest(
     @Path("id") int patientId, 
     @Path("dataType") String dataType, 
     @Header("X-XSRF-TOKEN") String token, 
     @Header("Cookie") String cookie, 
     @Body Request req); 
} 

而且我已經準備好去改裝:

mEndpointInterface = new Retrofit.Builder() 
      .baseUrl(BASE_URL) 
      .client(getUnsafeOkHttpClient()) 
      .addConverterFactory(GsonConverterFactory.create()) 
      .build().create(EndpointInterface.class); 

我認爲,現在呼籲mEndpointInterface.postRequest(1,「臺階」,「令牌「,」cookie「,新的SendStepsRequest(5));應該發送一個JSON看起來就像是:

{"steps":[{"value":5}]} 

但是所有的發送是

{} 

對我來說unlogical。我猜Gson不知道如何在類層次結構中下來,所以他不知道SendStepsRequest是Request的一個子類型。 我已經準備好了RuntimeTypeAdapterFactory,然後開始工作,但這對我來說很奇怪。 GSON不應該知道繼承嗎?所以我開始嘗試。

現在一些有趣的東西。我創建了一個類RequestWrapper此類:

public class RequestWrapper { 
    Request mRequest; 
} 

,並改變了我的接口來接受RequestWrapper此類,而不是請求你猜怎麼着!結果是:

{"mRequest":{"steps":[{"value":5}]}} 

所以他發現我的類是如何分層的,但是如果沒有RequestWrapper就無法做到這一點。

我也嘗試了不同的事情 - 我已經改變了我的接口,以接受SendStepsRequest對象,並更改列表< StepMeasurement>到列表<度量>。什麼改造發送到服務器?

{"steps":[{"value":5}]} 

所以,他再次檢測到Measurement類的子類型,並將其用作他應該使用的類型。

我的猜測是在Retrofit中存在一些錯誤,它會阻止在接口中傳遞的類的對象的正確序列化。你怎麼看?也許我做錯了什麼?

還有一件有趣的事 - 當我用Jackson代替Gson時觀察到了同樣的行爲。

+0

改造不會隱藏任何東西,Gson將你的pojo傳達給json。 [這裏閱讀](http://stackoverflow.com/questions/5800433/polymorphism-with-gson) – Blackbelt

+0

是的,我知道關於GSON - 只是一個心理上的快捷方式:) – karlkar

+0

嘗試將其更改爲「SendStepsRequest」並讓我們知道請問 – Fred

回答