我正在使用JSON
Library解析本地GSON
。这是我的json结构
{
"employees":[
{
"id":100,
"name":"Ranjith"
},
{
"id":101,
"name":"Satheesh"
}]
}
我必须在列表视图中显示它。这是我的代码
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();
}
当我运行这个IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1
。我正在使用一个单独的类来设置和获取json中的字段。如何解决这个问题。
答案 0 :(得分:3)
确保导入
import com.google.gson.stream.JsonReader
不要将其转换为String,将读者直接传递给gson。
Employee employee= gson.fromJson(reader, Employee.class);