2016-04-09 52 views
0

在这里苦苦挣扎,将包含对象 的JSON字符串转换为使用GSON的对象。Java - 使用Gso将Json字符串转换为对象

JSON数组

[ 
{"_id":"11111", 
    "_owner":"2222", 
    "name":"S32B - TankFever", 
    "__v":0, 
    "slots":[], 
    "members": 
    [ 
    {"_email":"[email protected]", 
    "key":"XXX", 
    "_id":"33333", 
    "accepted":false 
    }, 
    {"_email":"[email protected]", 
    "key":"XXX", 
    "_id":"44444", 
    "accepted":false} 
    ] 
}, and some more. 
] 

数组包含对象我称为 '的TimeSheet'。每个时间表都包含一个名为'Slot'和'Member'的对象数组。

的类

时间表

private String _owner; 
private String name; 
private Slot[] slots; 
private Member[] members; 

会员

private String _email; 
private String key; 
private boolean accepted; 

插槽(仍是空的),我想

守则,应该工作:

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

是什么让你认为它不起作用? – Savior

+0

@Pillar对不起,我完全忘了我会得到的错误信息! –

+1

这与JSON或Gson无关。您的回复信息流已关闭。 – Savior

回答

0

由于对象Type typeTimesheet 那么这个声明会产生异常

List<Timesheet2> inpList = new Gson().fromJson(jsonString, type); 

,而不是你应该使用相同的类作为type

List<Timesheet> inpList = new Gson().fromJson(jsonString, type); 
+0

感谢您与我一起在这里观看。我确实使用了正确的类,但是发布了错误的代码..我改变了我的帖子。 –

+0

它会产生异常'java.lang.IllegalStateException:closed'? – Savior

+0

你的答案完全错过了观点。 – Savior

相关问题