加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Gson:参数get serialized,即使它有@Expose(serialize =

发布时间:2020-12-15 04:38:10 所属栏目:Java 来源:网络整理
导读:我正在为 JSON API编写SDK,我遇到了一个看似奇怪的问题. API在POST数据验证方面非常严格,并且在更新资源时不允许存在某些参数,例如id.出于这个原因,我添加了@Expose(serialize = false)我的资源类的ID字段.然而,似乎它仍然序列化该字段,导致请求被拒绝.资源
我正在为 JSON API编写SDK,我遇到了一个看似奇怪的问题. API在POST数据验证方面非常严格,并且在更新资源时不允许存在某些参数,例如id.出于这个原因,我添加了@Expose(serialize = false)我的资源类的ID字段.然而,似乎它仍然序列化该字段,导致请求被拒绝.资源类大致如下:

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创建组织实例,将新创建的实例作为类参数保存到测试类,并调用更新方法,该方法将通过更新新资源来测试SDK的更新实现.这是它出错的地方.即使在新组织上调用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 / organization / {id})

解决方法

正如您在评论中提到的那样,@ Expose应该是比瞬态更好的选择.重要的是要注意默认的Gson实例不考虑@Expose注释!无论你设置什么选项,它都会忽略它.

如果要激活@Expose选项,则需要自定义Gson.根据您的上述代码,将其更改为:

public static final Gson PRETTY_PRINT_JSON = new GsonBuilder()
        .setPrettyPrinting()
        .excludeFieldsWithoutExposeAnnotation();
        .create();

您的@Expose(serialize = false)应该处于活动状态并在序列化期间排除.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读