Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue in parsing JSON using GSON library

Tags:

json

android

gson

I am working on parsing a local JSON using GSON Library.Here is my json structure

{
  "employees":[
  {
   "id":100,
   "name":"Ranjith"
  },
  {
   "id":101,
   "name":"Satheesh"
  }]
}

I have to display this in a list view.Here is my code

public void loadfromfile()
{
    try {
        AssetManager am = getAssets();
        InputStream is = am.open("sample.json");
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        Gson gson=new Gson();
        JsonReader reader=new JsonReader(br);
        reader.beginObject();
        while (reader.hasNext()) {

            String name = reader.nextName();

            if (name.equals("success")) {
                success =reader.nextBoolean();
            }

            else if(name.equals("employees")){
                reader.beginArray();
                while (reader.hasNext()) {

                    Employee employee= gson.fromJson(String.valueOf(reader), Employee.class);

                    emplist.add(employee);
                }
                reader.endArray();
            }
        }

     reader.endObject();
     reader.close();
        dataAdapter.notifyDataSetChanged();
    }catch (IOException ex){

        ex.printStackTrace();
    }

when i run this IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1.I am using a separate class to set and get fields in json.How to solve this problem.

like image 265
Ranjith Avatar asked Jan 17 '26 22:01

Ranjith


1 Answers

Make sure you import

 import com.google.gson.stream.JsonReader

Don't convert it to String, pass reader directly to gson.

Employee employee= gson.fromJson(reader, Employee.class);
like image 107
Orhan Obut Avatar answered Jan 20 '26 10:01

Orhan Obut