Reputation: 570
This is how my JSON
response looks
[
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
},
{
"id": 1,
"PhName": "sample string 2",
"Longitude": 3.1,
"Latitude": 4.1,
"ApplicationUserId": "sample string 5"
}
]
this is my retrofit interface call
@GET("/api/GPS")
@Headers({
"Accept: application/json"
})
Call<List<UserResponse>> search(@Query("search") String search,
@Header("Authorization") String auth);
Pojo Class
public class UserResponse {
@SerializedName("Id")
int id;
@SerializedName("UserName")
String phName;
@SerializedName("Longitude")
int lon;
@SerializedName("Latitude")
int lat;
@SerializedName("ApplicationUserId")
String appUserId;
//getters and setters
}
Retrofit declaration
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(PerformLogin.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
Getting data and using it
MyApiEndpointInterface apiService =
retrofit.create(MyApiEndpointInterface.class);
Call<List<UserResponse>> call = apiService.search(query,"Bearer "+token);
call.enqueue(new Callback<List<UserResponse>>() {
@Override
public void onResponse(Call<List<UserResponse>> call, Response<List<UserResponse>> response) {
List<UserResponse> userList = response.body();
Log.w("My App", response.message());
for (int i = 0; i <userList.size() ; i++) {
Log.w("My App", userList.get(i).getPhName()+""+i);
}
//mAdapter = new MyAdapter(getContext(),userList);
//mRecyclerView.setAdapter(mAdapter);
}
@Override
public void onFailure(Call<List<UserResponse>> call, Throwable t) {
Log.w("My App", t.getMessage());
}
});
my response
W/My App: OK
W/My App: null 0
W/My App: null 1
W/My App: null 2
W/My App: null 3
In this case I am suppose to receive four result from the search and the names are giving me null.
Is there anything I am doing wrong or a better solution to this?
Upvotes: 0
Views: 799
Reputation: 968
Your SerializedName
fields and the JSON fields don't match.
JSON: id
-> GSON: Id
JSON: PhName
-> GSON: UserName
Those two don't add up. You have to alter your annotations accordingly:
@SerializedName("id")
int id;
@SerializedName("PhName")
String phName;
Upvotes: 2
Reputation: 18112
You are using wrong serialize name. You are trying to assign value from node UserName
to phName
, which is not available. So, you are getting null.
Change
@SerializedName("UserName")
String phName;
with
@SerializedName("PhName") // change this
String phName;
Also, @SerializedName("Id")
should be @SerializedName("id")
. It's case sensitive.
Upvotes: 2