我有用于过滤由一个列表视图以下JSON响应片断first_name
,last_name
和email
。
"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": [
"[email protected]",
"[email protected]",
"[email protected]"
],
"filter_type": "select"
}
},
...
}
我的问题是first_name
,last_name
和email
是这意味着这些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": [
"[email protected]",
"[email protected]",
"[email protected]"
],
"filter_type": "select"
}
},
...
}
在这里,所使用的自定义过滤器age
,middle_name
和email
。尽管这些过滤器的名称可能不同,每个滤波器总是有key
,label
,order
,values
,和filter_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
}
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句