我想发出GET
请求并获取具有不同参数名称的对象:
{
"monday": {
"open_time": "06:30",
"close_time": "20:30"
},
"tuesday": {
"open_time": "06:30",
"close_time": "20:30"
},
"wednesday": {
"open_time": "06:30",
"close_time": "20:30"
},
"thursday": {
"open_time": "06:30",
"close_time": "20:30"
},
"friday": {
"open_time": "06:30",
"close_time": "20:30"
},
"saturday": {
"open_time": "08:00",
"close_time": "19:00"
},
"sunday": {
"open_time": "08:00",
"close_time": "19:00"
}
}
所以我做了DayEntity,但不知道如何使用我的星期一,星期二等? 服务jsonschema2pojo想要从周一到周日创建很多课程。
public class DayEntity {
@SerializedName("open_time")
@Expose
private String openTime;
@SerializedName("close_time")
@Expose
private String closeTime;
public void setOpenTime(String openTime) {
this.openTime = openTime;
}
public void setCloseTime(String closeTime) {
this.closeTime = closeTime;
}
UDP:如果GSON可以很好地解析它如何将它与Retrofit组合使用?我有WeekEntity,它会在成功返回NullPointer()
public class WeekEntity {
public HashMap<String, DayEntity> week;
public HashMap<String, DayEntity> getWeek() {
return week;
}
}
public void getBusinessHours(final Context context) {
RestAdapter restAdapter = formatHeader(NetworkConstants.BUSINESS_HOURS_URL);
restAdapter.create(ApiService.class).getBusinessHours(new Callback<WeekEntity>() {
@Override
public void success(WeekEntity weekEntity, Response response) {
Log.v("~~~~~success", weekEntity.getWeek().toString());
}
@Override
public void failure(RetrofitError error){
}
});
}
答案 0 :(得分:1)
最好是使用Gson插件for android studio将true
字符串转换为InnerClassEntity。
1)从here下载插件,并在文件/设置/插件
中安装到Android工作室2)安装完成后,创建类,然后右键单击/生成/ GsonFormat 并粘贴您的响应,然后单击确定。将生成自动响应对象(Json String)。保存完成。
3)你可以在onResponse中迭代数组然后像这样
JSON
当您初步改造时,请指定public void onResponse(Response<ModelClass> response, Retrofit retrofit) {
for (int i=0;i<response.body().getResponse().getArray_name().size();i++)
{
Log.i("TAG", "retro array :" + response.body().getResponse().getArray_name().get(i).getItem());
}
}
这样的内容。
ConverterFactory
并在 build.gradle
中retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
答案 1 :(得分:0)
class WeekEntity{
HashMap<String, DataEntity> week;
(...)
}
将你的json解析为这个你得到一张地图dayname -> DayEntity
。
答案 2 :(得分:0)
Gson 2.x能够使用Map<String, DataEntity>
答案 3 :(得分:0)
您的代码应该是这样的。
public class DayEntity {
public CheckTime monday;
public CheckTime tuesday;
public CheckTime wednesday;
public CheckTime thursday;
public CheckTime friday;
public CheckTime saturday;
public CheckTime sunday;
public class CheckTime
{
private String open_time;
private String close_time;
//add your setter and getter here
}
}