Han Tran
Han Tran

Reputation: 2093

Error when parse json object in java with Gson

I have a json string like this:

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

In java I wrote this code to decode that json string:

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);

But I always receive error:

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

What am I wrong?

Thanks :)

Upvotes: 0

Views: 354

Answers (2)

Samir Mangroliya
Samir Mangroliya

Reputation: 40426

you json string Result is not valid.see here valid or not

and it should be

[ { "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");

}

Upvotes: 0

deepa
deepa

Reputation: 2494

your json is not valid one..please check with some jsonvalidator whether the json is in correct format. To check the json Format refer the link

JSONFormat

To get the string from json, refer the below link as

AndroidJson

Parsing Json

I think it may helpful to you..

Upvotes: 1

Related Questions