嗨,大家好我有一个问题,解析我的嵌套json数组。这是我的示例JSON响应:Android解析嵌套json
{
"SUCCESS": true,
"DATA": [
{
"ShowData": [
{
"ShowTitle": "Episode 1",
"Category": "Comedy"
},
{
"ShowTitle": "Episode 1a",
"Category": "Drama"
},
{
"ShowTitle": "Mr. Right",
"Category": "Musical"
},
{
"ShowTitle": "The Making",
"Category": "Talk"
},
{
"ShowTitle": "Presscon",
"Category": "Comedy"
},
{
"ShowTitle": "Presscon 2",
"Category": "Drama"
},
{
"ShowTitle": "Episode 2",
"Category": "Comedy"
},
{
"ShowTitle": "Episode 2",
"Category": "Drama"
}
]
}
]
}
这是我到目前为止已经试过:
活动:
ArrayList<HashMap<String, String>> showsList
= Parser.getShowsResponseBody(response);
ArrayList<HashMap<String, String>> result = new ArrayList<>();
Set<String> titles = new HashSet<>();
for(HashMap<String, String> map : showsList) {
if(titles.add(map.get("Category"))) {
result.add(map);
}
}
分析器:
public static List<Show> getShowsResponseBody(Response response) {
BufferedReader reader = null;
StringBuilder sb = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
String result = sb.toString();
List<WorldShow> list = new ArrayList<>();
try {
JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("Data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
JSONArray arr = json_data.getJSONArray("ShowData");
for(int j = 0; j < arr.length(); j++) {
JSONObject innerData = arr.getJSONObject(j);
Show show = new Show(); // Create Object here
show.setShowTitle(innerData.getString("ShowTitle"));
show.setCategory(innerData.getString("Category"));
list.add(show); // Finally adding the model to List
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
我的预期成果是:
Comedy: Episode 1, Presscon, Episode 2
Drama: Episode 1a, Presscon 2, Episode 2
Musical: Mr. Right
Talk: The Making
但是当我运行应用程序,它显示在所有类别中的所有记录。我的代码看起来有什么问题?我已经使用HashSet去除重复的对象,但它仍然是一样的。任何帮助将非常感激!提前致谢!
你可能想要的东西像'的HashMap <字符串,收藏>'来存储多个显示每个类别。 –
JimmyB