If the properties of the model are private, Android cannot convert the JSON response to the model
•
Android
I tried to use retrofit on Android, but I encountered this problem. I want to get data from the API in JSON format and convert it into a model in my application
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 use testservice to retrieve data, it will not return an error, but will return the empty class of A. if I change the property of class A to public, it will be converted to the correct object a
Editing questions
This is the JSON example I want to convert to model a
{
"property1" : "content",
"property2" : 1
}
resolvent:
If you are using gson, use the expose annotation on the private field
Like:
@Expose
private String property1;
@Expose
private int property2;
If you want to use a different name for a variable, you can try using the serializedname annotation, for example:
@Expose
@SerializedName("property1")
private String p1;
@Expose
@SerializedName("property2")
private int p2;
I think if we don't publish the complete "a" course, it should be OK
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码