在这里努力转换包含对象的JSON字符串 使用GSON的对象。
JSON数组
[
{"_id":"11111",
"_owner":"2222",
"name":"S32B - TankFever",
"__v":0,
"slots":[],
"members":
[
{"_email":"mail@gmail.com",
"key":"XXX",
"_id":"33333",
"accepted":false
},
{"_email":"mail@hotmail.nl",
"key":"XXX",
"_id":"44444",
"accepted":false}
]
}, and some more.
]
数组包含我调用的对象' TimeSheet'。每个时间表都包含一系列对象,称为:' Slot'和'会员'。
课程
时间表
private String _owner;
private String name;
private Slot[] slots;
private Member[] members;
会员
private String _email;
private String key;
private boolean accepted;
Slot(仍然是空的)
代码我认为哪些应该有效:
String jsonString = response.body().string();
Type type = new TypeToken<List<Timesheet>>(){}.getType();
List<Timesheet> inpList = new Gson().fromJson(jsonString, type);
for (int i=0;i<inpList.size();i++) {
Timesheet x = inpList.get(i);
System.out.println(x);
}
我得到的错误(它没有说出关于Gson的任何信息,但它确实在调试中引发了异常)
04-09 23:13:17.242 1594-1594/com.example.jim.app I/System.out: java.lang.IllegalStateException: closed
04-09 23:13:17.242 1594-1594/com.example.jim.app I/System.out: at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java:378)
04-09 23:13:17.242 1594-1594/com.example.jim.app I/System.out: at okio.Buffer.writeAll(Buffer.java:956)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:92)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at okhttp3.ResponseBody.bytes(ResponseBody.java:83)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at okhttp3.ResponseBody.string(ResponseBody.java:109)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at com.example.jim.app.model.User.getOwnedTimesheets(User.java:169)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at com.example.jim.app.fragment.TimesheetsFragment.initializeTimesheetsListView(TimesheetsFragment.java:91)
04-09 23:13:17.243 1594-1594/com.example.jim.app I/System.out: at com.example.jim.app.fragment.TimesheetsFragment.onCreateView(TimesheetsFragment.java:73)
如果需要一些其他信息,我会尽快更新这个问题!
由于
答案 0 :(得分:0)
由于对象Type type
引用Timesheet
那么这个语句将生成异常
List<Timesheet2> inpList = new Gson().fromJson(jsonString, type);
相反,你应该使用与type
相同的类,即
List<Timesheet> inpList = new Gson().fromJson(jsonString, type);