这是JSON
响应的显示方式
[
{
"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"
}
]
这是我的改装界面调用
@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 retrofit = new Retrofit.Builder()
.baseUrl(PerformLogin.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
获取数据并使用它
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());
}
});
我的回复
W/My App: OK
W/My App: null 0
W/My App: null 1
W/My App: null 2
W/My App: null 3
在这种情况下,我想从搜索中收到四个结果,并且名称给我null。
我有什么问题或者更好的解决方案吗?
答案 0 :(得分:2)
您使用了错误的序列化名称。您正尝试将节点UserName
中的值分配给phName
,这是不可用的。所以,你得到了无效。
更改
@SerializedName("UserName")
String phName;
带
@SerializedName("PhName") // change this
String phName;
此外,@SerializedName("Id")
应为@SerializedName("id")
。这是区分大小写的。
答案 1 :(得分:2)
您的SerializedName
字段与JSON字段不匹配。
JSON:id
- &gt; GSON:Id
JSON:PhName
- &gt; GSON:UserName
这两个人没有加起来。您必须相应地更改注释:
@SerializedName("id")
int id;
@SerializedName("PhName")
String phName;