将嵌套的JSON解析/反序列化并将其保存到SQLite中,然后检索它

问题描述 投票:0回答:1

我使用GSON解析了一个嵌套的JSON(这是我第一次来,可能是错误的)。现在,我试图将其插入SQLite。找不到下一步需要写的内容。当我为插入编写for循环时,出现错误cannot find symbol class Country。找不到在线相关的指导,因此希望任何人都可以帮助您前进。

这就是问题的开始:

Country[] countriesArray = gson.fromJson(jsonString, Country[].class);
for (int i = 0; i < countriesArray.length(); i++) {
...
            }

countriesArray.length()被标记为错误:找不到符号类Country。

JSON中的一个对象:

[ 
   { 
      "name":"Afghanistan",
      "topLevelDomain":[ 
         ".af"
      ],
      "callingCodes":[ 
         "93"
      ],
      "capital":"Kabul",
      "region":"Asia",
      "subregion":"Southern Asia",
      "population":27657145,
      "latlng":[ 
         33.0,
         65.0
      ],
      "demonym":"Afghan",
      "area":652230.0,
      "gini":27.8,
      "timezones":[ 
         "UTC+04:30"
      ],
      "nativeName":"افغانستان",
      "numericCode":"004",
      "currencies":[ 
         { 
            "name":"Afghan afghani",
            "symbol":"؋"
         }
      ],
      "languages":[ 
         { 
            "name":"Pashto",
            "nativeName":"پښتو"
         },
         { 
            "name":"Uzbek",
            "nativeName":"Oʻzbek"
         },
         { 
            "name":"Turkmen",
            "nativeName":"Türkmen"
         }
      ],
      "translations":{ 
         "de":"Afghanistan",
      },
      "flag":"https://restcountries.eu/data/afg.svg",
      "cioc":"AFG"
   },

我编写的模型类仅用于所需的变量对象和数组。

模型类Country.Java

public class Country implements Parcelable {

    private String name;
    private String capital;
    private String region;
    private String subregion;
    private int population;
    private List<Double> latlng = new ArrayList<Double>();
    private double area;
    private double gini;
    private List<String> timezones = new ArrayList<String>();
    private List<Currency> currencies = new ArrayList<Currency>();
    private List<Language> languages = new ArrayList<Language>();
    private String flag;

    public Country() {}

//getters, setters, toString() and Parcelable methods
}

模型类Currency.Java

public class Currency implements Parcelable {

    private String name;
    private String symbol;

//getters, setters, toString() and Parcelable methods
}

模型类Language.Java

public class Language implements Parcelable {

    private String name;
    private String nativeName;

//getters, setters, toString() and Parcelable methods
}
android json sqlite gson
1个回答
0
投票

创建一个typeToken并将其传递给fromJson方法,如下所示

Type listType = new TypeToken<List<Country>>(){}.getType();
List<Country> countryList = gson.fromJson(jsonArray.toString(), listType);

0
投票

TypeToken解析期间使用Gson JSON设置返回对象类型

List<Country> countries  = gson.fromJson(jsonString, new TypeToken<List<Country>>(){}.getType());

对于(国家/地区:国家/地区,{//在这里进行数据库操作}

© www.soinside.com 2019 - 2024. All rights reserved.