Search code examples
androidjsonillegalstateexception

Android JSon error "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2"


I am getting JSon data from a web service, the sample data is given below:

[
  {
    "SectionId": 1,
    "SectionName": "Android"
  }
]

When i try to convert it, it throws an error, i am doing it as:

Data data = new Gson().fromJson(jsonDataFromWebService, Data.class);

My Section Class is:

class Section
{
    public int SectionId;
    public String SectionName;
}

class Data {
    public List<Section> sections;
}

The LogCat says:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2


Solution

  • The error explains whats wrong... u r returning an array and not a JSon object

    try as following:

    JSONArray ja = new JSONArray(jsonStringReturnedByService);
    
    Data sections = new Data();
    
    for (int i = 0; i < ja.length(); i++) {
        Section s = new Section();
        JSONObject jsonSection = ja.getJSONObject(i);
    
        s.SectionId = Integer.ValueOf(jsonSection.getString("SectionId"));
        s.SectionName = jsonSection.getString("SectionName");
    
       //add it to sections list
       sections.add(s);
    }
    
    return sections;