我正在为一个JSON API编写SDK,并且遇到了一个看似奇怪的问题。该API在POST数据验证方面非常严格,不允许在更新资源时出现某些参数,例如
id
。因此,我在我的资源类的ID字段上添加了@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将要POST到的URL中 (POST /organisation/{id}
)
@Expose
以便更好地控制它。 - Roemer