Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit Android can't convert JSON response to model if the model's properties are private

I tried using Retrofit on Android and I encountered this problem. I want to get data in JSON from an API and convert it into a model in my app.

This is my model

public class A {
   private String property1;
   private int property2;

   //default constructor, getter and setter below
}

This is my service

public interface TestService {
   @GET("/a")
   void getA(Callback<A> callback);
}

When I retrieve the data using TestService, it won't return an error but it will return an empty class of A. If I change the property of class A to public, then it will be converted to the right object A.

EDIT QUESTION

This is the JSON example that I want to convert into model A

{
   "property1" : "content",
   "property2" : 1
}
like image 392
Michael Avatar asked Dec 06 '25 06:12

Michael


1 Answers

Use Expose annotation on your private fields if you are using GSON.

Like :

@Expose
private String property1;

@Expose
private int property2;

If you want to use a different name for your variables, you can try SerializedName annotation like :

@Expose
@SerializedName("property1")
private String p1;

@Expose
@SerializedName("property2")
private int p2;

I think that should work, if not post your complete "A" class.

like image 79
arbrcr Avatar answered Dec 08 '25 19:12

arbrcr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!