android-使用GSON库解析JSON的问题

android-使用GSON库解析JSON的问题,第1张

概述我正在使用GSONLibrary解析本地JSON.这是我的json结构{"employees":[{"id":100,"name":"Ranjith"},{"id":101,"name":"Satheesh"}]}我必须在列表视图中显示.这是我的代码publicvoidloadfromf

我正在使用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);
总结

以上是内存溢出为你收集整理的android-使用GSON库解析JSON的问题全部内容,希望文章能够帮你解决android-使用GSON库解析JSON的问题所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1079157.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存