我正在通过改装和RXAndroid从android与我的REST API进行交互,我遇到了一个问题。
当我向我的'api / users / {id} / {id} / classes'发送GET请求时,我的api会回复一个用户类列表,如下所示:
{
"classes": [
{
"assignments": [
{
"asstype": 0,
"classs_id": 1,
"desc": "Read",
"due": "9/14/16",
"id": 1
}
],
"badge": 0,
"days": "W",
"id": 1,
"location": "W.Claire Harris Textiles 136A",
"name": "STS 1101",
"professor": "Stickel",
"time": "5:00 - 6:15",
"user_id": 1
},
{
"assignments": [],
"badge": 1,
"days": "TR",
"id": 2,
"location": "Atrium 201L",
"name": "HIST 2111",
"professor": "Pierce",
"time": "6:30 - 7:45",
"user_id": 1
}
]
}
我的界面如下所示:
@GET("api/users/{user_id}/classes")
Ovservable<List<Clazz>> getClasses(@Header("Authorization") String auth, @Path("user_id")int user_id);
我从我的片段中这样称呼它:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_classes, container, false);
Retrofit retrofit = new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(Sched.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RecyclerView classesRV = (RecyclerView)rootView.findViewById(R.id.classRec);
ClassInterface classAPI = retrofit.create(ClassInterface.class);
Observable<List<Class>> classes = classAPI.getClasses("Basic " +Base64.encodeToString("joyod3@gmail.com:nightman_420".getBytes(), Base64.NO_WRAP), 1);
classes.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Class>>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
@Override
public void onNext(List<Class> classes) {
classesRV.setAdapter(new ClassRecyclerViewAdapter(classes, getContext()));
classesRV.setLayoutManager(new LinearLayoutManager(getContext()));
}
});
return rootView;
}
My Class对象与getter和setter一起显示:
public class Class {
private int id;
private String name;
private int badge;
private String professor;
private String location;
private String days;
private String time;
private int user_id;
private List<Assignment> assignments;
public Class() {
}
不应该gson看到“类”:[]数组并从中解析对象?我做错了什么
答案 0 :(得分:1)
正如@CommonsWare所提到的,使用这个JSON响应结构,你需要一些中间类来保存Clazz
的集合(或者完全写一个自定义的反序列化器)。像这样:
public class ClassHolder {
List<Clazz> classes;
}
getClasses()
的返回类型会相应更改为Observable<ClassHolder>
。