2012-06-09 41 views
0

我有一个JSON字符串是这样的:错误时,在Java解析JSON对象与GSON

String result={[{"id":"2","fullname":"Course 1"},{"id":"3","fullname":"Course 2"}]} 

在java中我写了这个代码到JSON字符串解码:

public class Courses { 
public String id,name; 
} 
Gson gs = new Gson(); 
Type listType = new TypeToken<List<Courses>>(){}.getType(); 
List<Courses> listCourses= gs.fromJson(result, listType); 

但我总是收到错误:

06-09 04:21:11.614: E/AndroidRuntime(449): Caused by: java.lang.IllegalStateException: This is not a JSON Array.

我错了什么?

谢谢:)

回答

0

你json字符串Result is not validsee here有效与否

,它应该是

[ { "id": "2", "fullname": "Course 1" }, { "id": "3", "fullname": "Course 2" } ]

JSONArray jsonArray = new JSONArray(result); 
for (int i = 0; i < jsonArray.length(); i++) { 

    JSONObject objJson = jsonArray.getJSONObject(i); 
    int id = objJson.getInt("id"); 
    String fullName = objJson.getString("fullname"); 

} 
+0

感谢兄弟,你救我的时间:) –

1

您的JSON是无效one..please一些jsonvalidator的JSON是正确的格式进行检查。要检查JSON格式参考链接

JSONFormat

要想从JSON字符串,请参考以下链接为

AndroidJson

Parsing Json

我认为它可能对你有所帮助..