gpt4 book ai didi

java - GSON 解析多个相同类型的key

转载 作者:搜寻专家 更新时间:2023-11-01 08:20:59 24 4
gpt4 key购买 nike

我正在使用 Android 开发一个个人项目,我想使用 GSON 来解析包含我需要的数据的 JSON 文件。我有一个具有以下结构的本地 JSON 文件:

{
"Object1": {
"foo": "value1",
"bar": "value2",
"baz": "value3",
...
},
"Object2": {
"foo": "value4",
"bar": "value5",
"baz": "value6",
...
},
...
}

我已经制作了一个具有以下结构的对象类:

Class Object {
String data;
...
}

我将如何解析具有这种结构的 JSON 文件?

编辑:我使用的 JSON 文件非常大,它包含大约 400 多个对象类型的对象。我将不得不遍历每个对象以创建一个新的 JSONObject,但我不知道该怎么做。

最佳答案

在下面的解决方案中,我们将您在链接中提供的 JSON 转换为 JSONOject。然后我们得到 JSON 中包含的名称列表(“Abaddon”、“Archeri”、...)。一旦我们有了列表,我们就会遍历它。对于每个名称,我们都会获得与其关联的 JSON 对象。

然后我们使用GSON将每个对象转换成一个Demon对象。 Demon 类是使用 http://www.jsonschema2pojo.org/ 生成的如上所述。

由于 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
}
}

关于java - GSON 解析多个相同类型的key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51157509/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com