gpt4 book ai didi

java - Android:如何从对象名称可能更改的 JSON 响应中检索多个 JSON 对象?

转载 作者:行者123 更新时间:2023-11-29 22:41:23 24 4
gpt4 key购买 nike

我有以下 JSON 响应 fragment ,用于按 first_namelast_nameemail 过滤 ListView 。

"data": {

"filters": {
"first_name": {
"key": "first_name",
"label": "First Name",
"order": 1,
"values": [
"Shaun",
"Max",
"Tyler"
],
"filter_type": "select"
},
"last_name": {
"key": "last_name",
"label": "Last Name",
"order": 2,
"values": [
"Nash",
"Mally",
"Carick"
],
"filter_type": "select"
},
"email": {
"key": "email",
"label": "Email",
"order": 3,
"values": [
"shaun@email.com",
"max@email.com",
"tyler@email.com"
],
"filter_type": "select"
}
},

...

}

我的问题是 first_namelast_nameemail 是自定义过滤器,这意味着这些 JSON 对象名称可以更改。例如,另一个响应可能如下所示:

"data": {

"filters": {
"age": {
"key": "age",
"label": "Age",
"order": 1,
"values": [
"33",
"24",
"47"
],
"filter_type": "select"
},
"middle_name": {
"key": "middle_name",
"label": "Middle Name",
"order": 2,
"values": [
"Nicholas",
"Ava",
"George"
],
"filter_type": "select"
},
"email": {
"key": "email",
"label": "Email",
"order": 3,
"values": [
"shaun@email.com",
"max@email.com",
"tyler@email.com"
],
"filter_type": "select"
}
},

...
}

在这里,使用的自定义过滤器是 agemiddle_nameemail。虽然这些过滤器名称可能不同,但每个过滤器始终有一个 keylabelordervaluesfilter_type 字段。

我无法理解如何使用 GSON 正确解析此处的信息。我尝试研究将 JSON 用于 POJO 网站,但我不知道如何应用它,因为过滤器并不总是相同的。我也尝试这样做:

JSONObject dataObject = myJSON.getJSONObject("data");
if(dataObject.has("filters")){
JSONObject filterJSONObject = dataObject.getJSONObject("filters");
//I need to retrieve the keys/values for each filter here
}

但这只返回第一个过滤器对象而不是其余的。

任何帮助将不胜感激

最佳答案

我建议采用不同的方法。您可以像这样创建类(名称仅供示例,但字段名称很重要):

public static class Holder {
private final Filters data;

public Holder(Filters data) {
this.data = data;
}

public Filters getData() {
return data;
}
}

public static class Filters {
private final Map<String, Value> filters;

public Filters(Map<String, Value> filters) {
this.filters = filters;
}

public Map<String, Value> getFilters() {
return filters;
}
}

public static class Value {
private final String label;
private final int order;

public Value(String label, int order) {
this.label = label;
this.order = order;
}

public String getLabel() {
return label;
}

public int getOrder() {
return order;
}
}

以上结构将序列化到您的示例 json 中:

        Value value1 = new Value("label1", 1);
Value value2 = new Value("label2", 2);
Map<String, Value> data = new HashMap<>();
data.put("age", value1);
data.put("email", value2);
Filters filters = new Filters(data);

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Log.d("json", gson.toJson(new Holder(filters)));

这是日志输出:

{
"data": {
"filters": {
"age": {
"label": "label1",
"order": 1
},
"email": {
"label": "label2",
"order": 2
}
}
}
}

关于java - Android:如何从对象名称可能更改的 JSON 响应中检索多个 JSON 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004745/

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