2013-04-08 426 views
30

我想問一個關於在an​​droid上將jsonArray轉換爲StringArray的問題。這裏是我的代碼從服務器獲取jsonArray。將JSONArray轉換爲字符串數組

try { 
    DefaultHttpClient defaultClient = new DefaultHttpClient(); 
    HttpGet httpGetRequest = new HttpGet("http://server/android/listdir.php"); 
    HttpResponse httpResponse = defaultClient.execute(httpGetRequest); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8")); 

    String json = reader.readLine(); 

    //JSONObject jsonObject = new JSONObject(json); 
    JSONArray jsonArray = new JSONArray(json); 
    Log.d("", json); 

    //Toast.makeText(getApplicationContext(), json, Toast.LENGTH_SHORT).show(); 

} catch (Exception e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

而這是JSON。

[{ 「名稱」: 「IMG_20130403_140457.jpg」},{ 「名稱」: 「IMG_20130403_145006.jpg」},{ 「名稱」: 「IMG_20130403_145112.jpg」},{ 「名稱」:「IMG_20130404_085559 .JPG 「},{」 名 「:」 IMG_20130404_113700.jpg 「},{」 名 「:」 IMG_20130404_113713.jpg 「},{」 名 「:」 IMG_20130404_135706.jpg 「},{」 名 「:」 IMG_20130404_161501.jpg 「},{」 名 「:」 IMG_20130405_082413.jpg 「},{」 名 「:」 IMG_20130405_104212.jpg 「},{」 名 「:」 IMG_20130405_160524.jpg 「},{」 名 「:」 IMG_20130408_082456.jpg「} {「名」:「test.jpg放在」}]

我如何轉換jsonArray,我已經有了字符串數組,所以我可以得到字符串數組是這樣的:

array = {「IMG_20130403_140457.jpg」,「I​​MG_20130403_145006.jpg」,........,「test.jpg」};

謝謝你的幫助... :)

+2

如果你得到它,你應該接受一個答案。 – vinoth 2013-04-08 04:40:50

+0

爲什麼你想這樣做,浪費資源? – Nezam 2013-04-08 04:45:19

+1

@尼扎姆,對不起,你是什麼意思..? – andikurnia 2013-04-08 04:50:40

回答

38

看看這個tutorial 也可以解析上述JSON像

JSONArray arr = new JSONArray(yourJSONresponse); 
List<String> list = new ArrayList<String>(); 
for(int i = 0; i < arr.length(); i++){ 
    list.add(arr.getJSONObject(i).getString("name")); 
} 
+0

這會先轉換爲數組列表,然後我可以再次轉換爲StringArray,謝謝給出一個想法...(y) – andikurnia 2013-04-08 08:36:36

+0

你可以使用list.add(arr.getString(i))以及 – 2016-12-14 18:16:54

11
String[] arr = jsonArray.toString().replace("},{", " ,").split(" "); 
+6

這是不安全的: [ { 「名」: 「},{」 },... ] – youseeus 2016-07-18 12:11:26

+0

@youseeus爲什麼這個代碼成爲不安全? – andikurnia 2017-06-13 07:52:06

+0

問題是,如果一些字符串包含json(如「},{」),它也會被拆分。 – youseeus 2017-06-14 05:01:43

5

可以循環創建字符串

List<String> list = new ArrayList<String>(); 
for (int i=0; i<jsonArray.length(); i++) { 
    list.add(jsonArray.getString(i)); 
} 
String[] stringArray = list.toArray(new String[list.size()]); 
3

他再次是代碼:

// XXX satisfies only with this particular string format 
     String s = "[{\"name\":\"IMG_20130403_140457.jpg\"},{\"name\":\"IMG_20130403_145006.jpg\"},{\"name\":\"IMG_20130403_145112.jpg\"},{\"name\":\"IMG_20130404_085559.jpg\"},{\"name\":\"IMG_20130404_113700.jpg\"},{\"name\":\"IMG_20130404_113713.jpg\"},{\"name\":\"IMG_20130404_135706.jpg\"},{\"name\":\"IMG_20130404_161501.jpg\"},{\"name\":\"IMG_20130405_082413.jpg\"},{\"name\":\"IMG_20130405_104212.jpg\"},{\"name\":\"IMG_20130405_160524.jpg\"},{\"name\":\"IMG_20130408_082456.jpg\"},{\"name\":\"test.jpg\"}]"; 
     s = s.replace("[", "").replace("]", ""); 
     s = s.substring(1, s.length() - 1); 
     String[] split = s.split("[}][,][{]"); 
     for (String string : split) { 
      System.out.println(string); 
     } 
+0

嗯,我想如果代碼是動態數據..但是謝謝你的回答... :) – andikurnia 2013-04-08 05:00:15

+0

@andikurnia 您必須以's'格式獲取動態數據,請接受如果它適合你的話,答案是肯定的。 – Visruth 2013-04-08 06:25:14

+0

我認爲如果在JSON內有括號(\ [)),這會失敗。 – 2014-10-24 21:31:47

9
public static String[] getStringArray(JSONArray jsonArray) { 
    String[] stringArray = null; 
    if (jsonArray != null) { 
     int length = jsonArray.length(); 
     stringArray = new String[length]; 
     for (int i = 0; i < length; i++) { 
      stringArray[i] = jsonArray.optString(i); 
     } 
    } 
    return stringArray; 
} 
+2

代碼只是答案,雖然它們可能是正確的,但很少像解釋原因一樣提供信息。考慮在你的文章中添加一些評論或解釋。 – indivisible 2014-06-05 09:18:09

+1

檢查「jsonArray」在使用後是否爲空 - 是錯誤的,因爲您可能在檢查之前獲得NPE。 – 2014-11-29 23:50:58

4

你去那裏:

String tempNames = jsonObj.names().toString(); 
String[] types = tempNames.substring(1, tempNames.length()-1).split(","); //remove [ and ] , then split by ',' 
+0

這是危險的,原因可能是其他發生的「,」在數據 – youseeus 2017-08-14 13:28:11

12

簡單且正確的代碼是:

public static String[] toStringArray(JSONArray array) { 
    if(array==null) 
     return null; 

    String[] arr=new String[array.length()]; 
    for(int i=0; i<arr.length; i++) { 
     arr[i]=array.optString(i); 
    } 
    return arr; 
} 

使用List<String>是不是一個好主意,因爲你知道數組的長度。 注意到它使用for條件中的arr.length來避免在每個循環上調用一個方法,即array.length()

+0

這是很好的方法,謝謝。哈哈,因爲這是一個很長的回答,我會在我的片段中注意到這一點。 – andikurnia 2017-08-02 01:14:29

0

僅使用便攜式JAVA API。http://www.oracle.com/technetwork/articles/java/json-1973242.html


try (JsonReader reader = Json.createReader(new StringReader(yourJSONresponse))) { 
     JsonArray arr = reader.readArray(); 

     List<String> l = arr.getValuesAs(JsonObject.class) 
      .stream().map(o -> o.getString("name")).collect(Collectors.toList()); 
    } 
+0

https://gist.github.com/leonardossz/385adfeb98ec8989f68445be2125a6a0 – Leo 2017-01-10 09:26:29

1

可以輸入JSON陣列這個函數得到作爲字符串數組輸出

例如輸入 - { 「性別」:[ 「男」, 「女」] }

輸出 - { 「男」, 「女」}

private String[] convertToStringArray(Object array) throws Exception { 
    return StringUtils.stripAll(array.toString().substring(1, array.toString().length()-1).split(",")); 
} 
+0

儘管您可能已經解決了此用戶的問題,但僅有代碼的答案對於未來出現此問題的用戶來說並不是非常有用。請編輯您的答案,以解釋爲什麼您的代碼可以解決原始問題。 – 2017-01-29 08:15:07

1

一個現成的使用方法:

/** 
* Convert JSONArray to ArrayList<String>. 
* 
* @param jsonArray JSON array. 
* @return String array. 
*/ 
public static ArrayList<String> toStringArrayList(JSONArray jsonArray) { 

    ArrayList<String> stringArray = new ArrayList<String>(); 
    int arrayIndex; 
    JSONObject jsonArrayItem; 
    String jsonArrayItemKey; 

    for (
    arrayIndex = 0; 
    arrayIndex < jsonArray.length(); 
    arrayIndex++) { 

    try { 
     jsonArrayItem = 
     jsonArray.getJSONObject(
      arrayIndex); 

     jsonArrayItemKey = 
     jsonArrayItem.getString(
      "name"); 

     stringArray.add(
     jsonArrayItemKey); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    } 

    return stringArray; 
}