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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With