2013-04-08 433 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; 
}