我正在爲JSON API編寫一個SDK,我遇到了一個看似奇怪的問題。該API在POST數據驗證方面相當嚴格,並且在更新資源時不允許某些參數存在,如id
。爲此,我添加了@Expose(serialize = false)
我的資源類的ID字段。但它似乎仍然序列化該字段,導致請求被拒絕。資源類大致如下:Gson:即使它具有@Expose(serialize = false)參數獲得序列化
public class Organisation extends BaseObject
{
public static final Gson PRETTY_PRINT_JSON = new GsonBuilder()
.setPrettyPrinting()
.create();
@Expose(serialize = false)
@SerializedName("_id")
private String id;
@SerializedName("email")
private String email;
@SerializedName("name")
private String name;
@SerializedName("parent_id")
private String parentId;
public String toJson()
{
return PRETTY_PRINT_JSON.toJson(this);
}
}
我的單元測試通過API創建的Organisation
一個實例,保存新創建的實例來測試類的類參數並調用將測試更新的更新方法通過更新新資源來實現SDK。這是它出錯的地方。儘管在新的Organisation
上調用toJson()
方法將其串行化爲JSON以獲取更新請求,但_id
字段仍然存在,導致API拒絕更新。測試代碼如下。注意代碼中的註釋。
@Test
public void testCreateUpdateAndDeleteOrganisation() throws RequestException
{
Organisation organisation = new Organisation();
organisation.setParentId(this.ORGANISATION_ID);
organisation.setName("Java Test Organisation");
Organisation newOrganisation = this.MySDK.organisation.create(organisation);
this.testOrganisation(newOrganisation);
this.newOrganisation = newOrganisation;
this.testUpdateOrganisation();
}
public void testUpdateOrganisation() throws RequestException
{
// I tried setting ID to null, but that doesn't work either
// even though I've set Gson to not serialise null values
this.newOrganisation.setId(null);
this.newOrganisation.setName(this.newName);
// For debugging
System.out.println(this.newOrganisation.toJson());
Organisation updatedOrganisation = this.MySDK.organisation.update(this.newOrganisation.getId(), this.newOrganisation);
this.testOrganisation(updatedOrganisation);
assertEquals(newOrganisation.getName(), this.newName);
this.testDeleteOrganisation();
}
任何人都可以發現我做錯了什麼嗎?我有一種感覺,它與該實例已經擁有/具有ID值的事實有關,但如果我明確地告訴它不要將它串行化,那麼這應該不重要?
在此先感謝您的幫助。
編輯:在this.MySDK.organisation.update(this.newOrganisation.getId(), this.newOrganisation);
,不編輯組織實例。給定的ID僅僅添加到SDK將發佈到的URL(POST /organisation/{id}
)
試着讓它變成'transient'而不是 –
@ cricket_007我之前做過,但是在反序列化時忽略了它。我用'@ Expose'有更多的控制權 –
看過? https://futurestud.io/tutorials/gson-model-annotations-how-to-ignore-fields-with-expose –