2016-07-04 34 views
0

我想实现当我填充JSON数组列表视图我的旧代码,但我目前的JSON没有指定数组,整体JSON是一个数组...JSON对象GSON到列表

有人可以告诉我如何将我的代码转换为像这样使用JSON?

https://api-v2.hearthis.at/categories/drumandbass/?page=15&count=2

代码使用GSON,我的老:

protected List<Model> doInBackground(String... params) { 
    HttpURLConnection connection = null; 
    BufferedReader reader = null; 
    try { 
    URL url = new URL(params[0]); 
    connection = (HttpURLConnection) url.openConnection(); 
    connection.connect(); 
    InputStream stream = connection.getInputStream(); 
    reader = new BufferedReader(new InputStreamReader(stream)); 
    StringBuffer buffer = new StringBuffer(); 
    String line =""; 
    while ((line = reader.readLine()) != null){ 
     buffer.append(line); 
    } 

    String finalJson = buffer.toString(); 

    JSONObject parentObject = new JSONObject(finalJson); 
    JSONArray parentArray = new JSONArray("arrayname"); 

    List<Model> dataModelList = new ArrayList<>(); 

    Gson gson = new Gson(); 
    for(int i=0; i<parentArray.length(); i++) { 
     JSONObject finalObject = parentArray.getJSONObject(i); 

     Model modelList = gson.fromJson(finalObject.toString(), Model.class); 
     dataModelList.add(modelList); 
    } 
    return dataModelList; 
    } catch (MalformedURLException e) { 
    e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } finally { 
    if(connection != null) { 
     connection.disconnect(); 
    } 
    try { 
     if(reader != null) { 
     reader.close(); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
return null; 
} 

回答

1

而不是这样做:

JSONObject parentObject = new JSONObject(finalJson); 
JSONArray parentArray = new JSONArray("arrayname"); 

只是这样做:

JSONArray parentArray = new JSONArray(finalJson); 
+0

我你,但THX之前想通了,答案接受,因为它是100%正确的 – ramzixp

1

如果我理解正确的问题,我想你有麻烦解析谁的名字不与键指定的数组。所以,一个简单但不这样做的一个很好的办法是,当你创建finalJson这样的:

String finalJson = buffer.toString(); 

只需添加一行检查它是否包含数组打开支架,像这样:

if(finalJson.contains("[")){ 
finalJson = finalJson.replace("[","{ 
    "arrayname": ["); 
} 

此外,请适当关闭阵列。

if(finalJson.contains("]")){ 
finalJson = finalJson.replace("]","] 
}"); 
} 

这样,你将有一个数组解析的名称,我想这就是你要找的。但是如果你的Json中有一个以上的数组,那么这种方法可能会失败,在这种情况下,你必须使用startsWith & endsWith字符串方法给你的数组命名。但是,就目前而言,从你的Json看起来,这是行得通的。