我正在使用GSON Library解析本地JSON.这是我的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时:预期为BEGIN_OBJECT但在第1行第1列处为STRING.我正在使用一个单独的类来设置和获取json中的字段.
解决方法:
确保您导入
import com.google.gson.stream.JsonReader
不要将其转换为String,将阅读器直接传递给gson.
Employee employee= gson.fromJson(reader, Employee.class);