我正在Android中处理一个个人项目,我想使用GSON解析包含所需数据的JSON文件。 我有一个具有以下结构的本地JSON文件:
{
"Object1": {
"foo": "value1",
"bar": "value2",
"baz": "value3",
...
},
"Object2": {
"foo": "value4",
"bar": "value5",
"baz": "value6",
...
},
...
}
我已经制作了一个具有以下结构的Object类:
Class Object {
String data;
...
}
我如何使用这种结构来解析此JSON文件?
编辑:我使用的JSON文件非常大,它包含大约400+个这些类型为Object的对象。我将不得不遍历每个对象以创建一个新的JSONObject,但是我不知道该怎么做。
答案 0 :(得分:3)
在下面的解决方案中,我们将您在链接中提供的JSON转换为JSONOject。然后,我们获取JSON中包含的名称列表(“ Abaddon”,“ Archeri”,...)。一旦有了列表,我们就可以遍历列表。对于每个名称,我们都会获得与之关联的JSON对象。
然后,我们使用GSON将每个对象转换为Demon对象。如上所述,已使用http://www.jsonschema2pojo.org/生成了Demon类。
由于JSON中的所有对象都具有相同的结构,因此我们只需要一个类就可以对每个对象进行反序列化。
反序列化器
public List<Demon> deserialize(String json) {
try {
JSONObject jsonObject = new JSONObject(json);
final JSONArray names = jsonObject.names();
final List<Demon> demons = new ArrayList<>();
final Gson gson = new Gson();
Demon demon;
for (int i = 0; i < names.length(); i++) {
demon = gson.fromJson(jsonObject.get(names.getString(i)).toString(), Demon.class);
demons.add(demon);
}
return demons;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
恶魔课
public class Demon {
@SerializedName("ailments")
@Expose
public String ailments;
@SerializedName("align")
@Expose
public String align;
@SerializedName("code")
@Expose
public Integer code;
@SerializedName("inherits")
@Expose
public String inherits;
@SerializedName("lvl")
@Expose
public Integer lvl;
@SerializedName("pcoeff")
@Expose
public Integer pcoeff;
@SerializedName("race")
@Expose
public String race;
@SerializedName("resists")
@Expose
public String resists;
@SerializedName("skills")
@Expose
public List<String> skills = null;
@SerializedName("source")
@Expose
public List<String> source = null;
@SerializedName("stats")
@Expose
public List<Integer> stats = null;
public Demon(){
// Default constructor
}
}