2015-09-02 38 views
0

为了2个JSON阵列结合到一个予使用下面的代码(输入数据areJSON该wereconverted为一个字符串数组)如何结合以JSON数组

private static String combineData(String Data, String data){ 
    if (empty(data)) 
     data = Data; 
    else { // need to append the data 
     try { 
// first, convert the strings back to JSON objects 
      JSONObject jsonObj1 = new JSONObject(data); // existing data 
      JSONObject jsonObj2 = new JSONObject(Data); // new data 
      // Getting Array of Providers 
      String fieldName = context.getString(R.string.JSON_COMP_RECORDS); 
// Second, get the array out of the JSON object 
      JSONArray record1 = jsonObj1.getJSONArray(fieldName); 
      JSONArray record2 = jsonObj2.getJSONArray(fieldName); 
// Third, join them into one array 
      JSONArray arr = new JSONArray(); 
// LOOP 1 - get individual JSON objects 
      for (int i = 0; i < record1.length(); i++) { 
       JSONObject c; 
       try { 
        c = record1.getJSONObject(i); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
        return data; 
       } 
       arr.put (c); 
      } 
// LOOP 1 - get individual JSON objects 
      for (int i = 0; i < record2.length(); i++) { 
       JSONObject c; 
       try { 
        c = record2.getJSONObject(i); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
        return data; 
       } 
       arr.put (c); 
      } 
      JSONObject json = new JSONObject(); 
      json.put (context.getString(R.string.JSON_COMP_RECORDS), arr); 
      data = json.toString(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
    return data; 
} 

不知是否有一种方法可以做得更有效率,并摆脱2循环?

+0

它看起来比以前我无助的评论更加紧密,是 - 创建一个新的功能。你只需要在函数中使用for循环。您必须将String数据传递给它,因为这是catch的一部分(我不喜欢在函数内传递变量,但是很好)。您可以返回c,然后将其放入数组中,而不是传递数组。我会把它写成答案,但是我的Java很生疏,所以我会把它留给其他人。 – dgBP

+0

@SagePawan。谢谢,它工作 – Zvi

回答

0

这个怎么样?你可以把JSONObject的直接诠释另一个数组

JSONArray record1 = jsonObj1.getJSONArray(fieldName); 
JSONArray record2 = jsonObj2.getJSONArray(fieldName); 
for (int i = 0; i < record1.length(); i++) { 
    JSONObject c; 
    try { 
      c = record1.getJSONObject(i); 
    } catch (JSONException e) { 
      e.printStackTrace(); 
      return data; 
    } 
    record2.put (c); 
} 
0

希望这有助于

JSONArray record1 = jsonObj1.getJSONArray(fieldName); 
JSONArray record2 = jsonObj2.getJSONArray(fieldName); 

for (int i = 0; i < record1.length(); i++) {  
    record2.put(record1.getJSONObject(i)); 
}