如何在 Android Retrofit 中忽略 JSON 元素

How to ignore a JSON element in Android Retrofit

我正在开发一个 Android 应用程序,它使用 Android Retrofit 发送 JSON(它将 POJO class 转换为 JSON)。它工作正常,但我需要在从 POJO class 发送 JSON 一个元素时忽略它。

有人知道任何 Android Retrofit 注释吗?

例子

POJO Class:

public class sendingPojo
{
   long id;
   String text1;
   String text2;//--> I want to ignore that in the JSON

   getId(){return id;}
   setId(long id){
     this.id = id;
   }

   getText1(){return text1;}
   setText1(String text1){
     this.text1 = text1;
   }

   getText2(){return text2;}
   setText2(String text2){
     this.text2 = text2;
   }


}

接口发送器 ApiClass

 public interface SvcApi {

 @POST(SENDINGPOJO_SVC_PATH)
 public sendingPojo addsendingPojo(@Body sendingPojo sp);

}

知道如何忽略 text2 吗?

用 @Expose注解,如:

@Expose private String id;

省略任何您不想序列化的字段。然后以这种方式创建您的 Gson 对象:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

如果您不想使用 new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(),我找到了替代解决方案。

只需在我需要忽略的变量中包含 transient

所以,POJO class 最后:

public class sendingPojo {
    long id;
    String text1;
    transient String text2;//--> I want to ignore that in the JSON

    getId() {
        return id;
    }

    setId(long id) {
        this.id = id;
    }

    getText1() {
        return text1;
    }

    setText1(String text1) {
        this.text1 = text1;
    }

    getText2() {
        return text2;
    }

    setText2(String text2) {
        this.text2 = text2;
    }
}

希望对您有所帮助

您可以通过将 GSONBuilder 中的 GSON 对象添加到您的 ConverterFactory 来配置 Retrofit,请参阅下面的示例:

private static UsuarioService getUsuarioService(String url) {
    return new Retrofit.Builder().client(getClient()).baseUrl(url)
            .addConverterFactory(GsonConverterFactory.create(getGson())).build()
            .create(UsuarioService.class);
}

private static OkHttpClient getClient() {
    return new OkHttpClient.Builder().connectTimeout(5, MINUTES).readTimeout(5, MINUTES)
            .build();
}

private static Gson getGson() {
    return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
}

要忽略字段元素,只需将 @Expose(deserialize = false, serialize = false) 添加到您的属性或 none,对于(反)序列化您的字段元素,您可以添加 @Expose()为您的属性添加空值的注释。

@Entity(indexes = {
        @Index(value = "id DESC", unique = true)
})
public class Usuario {

    @Id(autoincrement = true)
    @Expose(deserialize = false, serialize = false) 
    private Long pkey; // <- Ignored in JSON
    private Long id; // <- Ignored in JSON, no @Expose annotation
    @Index(unique = true)
    @Expose
    private String guid; // <- Only this field will be shown in JSON.

如果您使用的是 Kotlin + Retrofit + Moshi (我测试过这个) 如果您想有条件地忽略字段,可以将其设置为空。

data class  User(var id: String,  var name: string?)

val user = User()
user.id = "some id"
user.name = null

生成的 Json 将是

user{
"id": "some id"
}