繁体   English   中英

将json文件中的json数组解析为java ArrayList

[英]Parsing a json array in a json file into a java ArrayList

我有这个Json文件:

  1. States.json

      [ { "cod": "Z100", "name": "ALBANIA", "statoSovrano": "", "Continent": "EUROPA" }, { "cod": "Z101", "name": "ANDORRA", "statoSovrano": "", "Continent": "EUROPA" }, { "cod": "Z102", "name": "AUSTRIA", "statoSovrano": "", "Continent": "EUROPA" }, { "cod": "Z103", "name": "BELGIO", "statoSovrano": "", "Continent": "EUROPA" } ] 

我想使用gson将上面的json数组解析为java ArrayList,以便在之后执行其他操作。 因此,我创建了此类:

2. Country.java

public class Country extends ArrayList<Country>{
  private String name;
  private String cod;
  private String Continent;
  private String statoSovrano;

  Country(String c, String n,String s, String i) {
    name = n;
    cod = c;
    Continent = i;
    statoSovrano =s;
  }


  public String getName() {
    return name;
  }

  public String getIso() {
    return cod;
  }

  public String getContinent() {
    return Continent;
  }

  public String getStatoSovrano() {
    return statoSovrano;
  }
}

但是用这种方法:

AssetManager assetManager = getAssets();
            InputStream ims = assetManager.open("states.json");
            Reader reader = new InputStreamReader(ims);
            Gson gson1=new GsonBuilder().create();

            Type listType =new TypeToken<ArrayList<Country>>()  {   }.getType();
            ArrayList<Country> countries = gson1.fromJson(reader,listType);

最后一行引发错误:


com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 4 path $[0]        

我的文件json不是对象,为什么会出现此错误?

检查您的国家/地区定义-由于某些原因,您扩展了ArrayList:

公共类Country 扩展ArrayList {

粗体部分使Gson认为您所在的国家/地区是某种列表,这就是为什么它期望BEGIN_ARRAY

将类签名更改为

public class Country {

并且您的代码将正常工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM