JSONストリングを取得してAndroidアプリで使用するときに、いくつかの問題に直面しています。Android - レトロフィットを使用した配列タイトルのないJSONの解析
public class Category2 {
@SerializedName("_id")
private String _id;
@SerializedName("name")
private String name;
@SerializedName("tasks")
private int tasks;
public Category2(String _id, String name, int tasks) {
this._id = _id;
this.name = name;
this.tasks = tasks;
}
public String get_id(){
return _id;
}
public void set_id(String _id){
this._id = _id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public int getTasks() {
return tasks;
}
public void setTasks(int tasks){
this.tasks = tasks;
}
}
そして私は、私が改造要求から取得カテゴリ2のリストは、基本的には、クラスと呼ばれるCategoryResponseを持っています:だから、私は、カテゴリが持っている必要があり、私はすべてのフィールドを定義した、このクラスのカテゴリ2を、持っている
JSON文字列が上記のようなものである場合には{"genres":[{"id":28,"name":"Action"},{"id":12,"name":"Adventure"}]}
を:
public class CategoryResponse {
private List<Category2> results;
public List<Category2> getResults() {
return results;
}
public void setResults(List<Category2> results) {
this.results = results;
}
}
は、一般的に私はそれはのような項目のリストだ場合でも、結果の名前を持つJSON文字列を扱います私はリストの宣言上記のリスト結果の直列化を追加します。
@SerializedName("genres")
そして、私は私のGETメソッド宣言したときにそれだけで正常に動作します:
@GET("/v3/projects/{projectId}/categories/")
Call<CategoryResponse> getProjectCategories(@Query("projectId") String projectId, @Header("Token") String token);
をそして、私は私の活動でそれを呼び出します。
[
{
"_id": "59a6b18b2ba5c14bb76f28c8",
"createdAt": "2017-08-30T12:37:31.885Z",
"updatedAt": "2017-08-30T12:37:31.885Z",
"projectId": "598cbc74a1d0e57722ca98d1",
"companyId": "5602eb7ce49c9cd70409f206",
"name": "Arquitetura",
"__v": 0,
"tasks": 0
},
{
"_id": "59a6b1be2ba5c14bb76f28c9",
"createdAt": "2017-08-30T12:38:22.407Z",
"updatedAt": "2017-08-30T12:38:22.407Z",
"projectId": "598cbc74a1d0e57722ca98d1",
"companyId": "5602eb7ce49c9cd70409f206",
"name": "Manutenção",
"__v": 0,
"tasks": 0
}
]
01:
categoryService =
CategoryClient.getClient().create(CategoryService.class);
Call<CategoryResponse> call = categoryService.getProjectCategories(projectId,token);
call.enqueue(new Callback<CategoryResponse>() {
@Override
public void onResponse(Call<CategoryResponse> call, Response<CategoryResponse> response) {
//int statusCode = response.code();
listCategories = new ArrayList<>();
listCategories = response.body().getResults();
System.out.println("Size: " + response.body().getResults().size());
}
@Override
public void onFailure(Call<CategoryResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
は、しかし、私は、カテゴリのために今持っていることは、このようなものです
結果リストの名前をシリアル化することができず、 "response.body.GetResults()"を呼び出すとnullが返されます。あなたのサービスコードで
'Category2'コピーコンストラクタを削除してください。使用可能なコピーコンストラクターがある場合、新しい 'Category2'クラスオブジェクトを作成すると、デフォルトのConstructrorは呼び出されません。これを試して、それが動作するかどうか教えてください –