Alb*_*spo 19 android json retrofit
我正在开发一个使用Android Retrofit发送JSON的Android应用程序(它在JSON中转换POJO类).它工作正常,但我需要忽略从POJO类发送JSON一个元素.
有谁知道任何Android Retrofit注释?
例
POJO课程:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
接口发件人ApiClass
public interface SvcApi {
@POST(SENDINGPOJO_SVC_PATH)
public sendingPojo addsendingPojo(@Body sendingPojo sp);
}
Run Code Online (Sandbox Code Playgroud)
知道如何忽略text2吗?
Alb*_*spo 17
如果你不想使用,我找到了另一种解决方案new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().
只包含transient在我需要忽略的变量中.
所以,POJO课最后:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我希望它有所帮助
nik*_*kar 15
使用@Expose注释标记所需的字段,例如:
@Expose private String id;
Run Code Online (Sandbox Code Playgroud)
省去您不想序列化的任何字段.然后以这种方式创建您的Gson对象:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Run Code Online (Sandbox Code Playgroud)
您可以通过将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();
}
Run Code Online (Sandbox Code Playgroud)
要忽略字段元素,只需将@Expose(deserialize = false,serialize = false)添加到属性或不添加,并且对于(de)序列化字段元素,可以将带有空值的@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.
Run Code Online (Sandbox Code Playgroud)