我在结构中有一个JSon文件:
[
{
"name": "north america",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "south america",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "north europe",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "west europe",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "east europe",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "south europe",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "north africa",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "south africa",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "north asia",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "west asia",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "east asia",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "southeast asia",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "south asia",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
},
{
"name": "oceania",
"population": 10,
"wealth": 0,
"education": 0,
"corruption": 0
}
]首先,我使用Gson解析我的Json文件。我想要做的是将数据保存为JsonArray
我写的是:
final Land[] landInfo = new Gson().fromJson(getClass().getResource("../res/LandInfo.json").toExternalForm(), Land[].class)这告诉我Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
我的土地课:
public class Land {
private String name;
private int population;
private int wealth;
private double education;
private double corruption;
public String getName() {
return name;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
public int getWealth() {
return wealth;
}
public void setWealth(int wealth) {
this.wealth = wealth;
}
public double getEducation() {
return education;
}
public void setEducation(double education) {
this.education = education;
}
public double getCorruption() {
return corruption;
}
public void setCorruption(double corruption) {
this.corruption = corruption;
}
}为什么我要从格式良好的Json文件中获取数组输出呢?
发布于 2016-08-03 21:04:41
问题是
getClass().getResource("../res/LandInfo.json").toExternalForm()返回表示资源位置的字符串,而不是资源的内容。所以,您正在尝试解析字符串,例如
file:/[your project location]/classes/res/LandInfo.json正如您所看到的,这是无效的JSON,它正在导致错误。
要解决这个问题,可以使用fromJson(Reader json, Class<T> classOfT)。因此,创建流,它将负责从json文件中读取数据,并将其与读取器一起包装并传递给fromJson方法。
你的代码看起来就像
InputStream in = getClass().getResourceAsStream("../res/LandInfo.json");
Land[] landInfo = new Gson().fromJson(new InputStreamReader(in, "UTF-8"), Land[].class);https://stackoverflow.com/questions/38751396
复制相似问题