我试图用内部专业列表解析json 我有 JSON 格式:
{
"response" : [
{
"f_name" : "иВан",
"l_name" : "ИваноВ",
"birthday" : "1987-03-23",
"avatr_url" : "http://url/upimg/author/451/image.jpg",
"specialty" : [{
"specialty_id" : 101,
"name" : "Менеджер"
}]
},
{
"f_name" : "Петр",
"l_name" : "петроВ",
"birthday" : null,
"avatr_url" : "http://url/upimg/author/489/image.jpg",
"specialty" : [{
"specialty_id" : 101,
"name" : "Менеджер"
},
{
"specialty_id" : 102,
"name" : "Разработчик"
}]
},....
我通过这种方法获取数据:
instance = this;
Room.databaseBuilder(this, AppDatabase.class, "database").build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
readerApi = retrofit.create(ReaderApi.class);
}
public static ReaderApi getApi() {
return readerApi;
}
....
public interface ReaderApi {
@GET("testTask.json")
Call<ResponseModel> getJSON();
}
没关系,我可以正确获取所有员工数据。
但是我无法获得特色数组。 Specialty_id和Specialty_name =在调试中为null。
我的响应模型:
public class ResponseModel {
private ArrayList<Employee> employees = new ArrayList<>();
private ArrayList<Specialty> specialties = new ArrayList<>();
@Ignore
public ResponseModel(ArrayList<Employee> employees, ArrayList<Specialty> specialties) {
this.employees = employees;
this.specialties = specialties;
}
some getters...
...
}
我的员工模型:
@Entity(indices = {@Index(value = {"f_name", "l_name", "birthday",
"avatarLink"})})
public class Employee {
@PrimaryKey(autoGenerate = true)
public int employeeId;
public String f_name;
public String l_name;
public String birthday;
@Ignore
private int age;
public String avatarLink;
@Ignore
private List<Specialty> specialty;
public Employee(int employeeId, String f_name, String l_name, String birthday, String avatarLink) {
this.employeeId = employeeId;
this.f_name = f_name;
this.l_name = l_name;
this.birthday = birthday;
this.avatarLink = avatarLink;
}
答案 0 :(得分:1)
问题是参数JSON和类字段的名称不匹配。 正确地:
如果JSON具有以下内容:
"f_name" : "Name",
"l_name" : "LName",
"birthday" : String,
"avatr_url" : "URL",
"specialty" : [{
"specialty_id" : int,
"name" : "Name"
}...
在课堂上,我们需要使用这个:
public String f_name;
public String l_name;
public String birthday;
....
public int specialty_id;
public String name;
....
public Specialty(int specialty_id, String name) {
this.specialty_id = specialty_id;
this.name = name;
}
谢谢@Leon的回答