【问题标题】:Convert JSONArray to String Array将 JSONArray 转换为字符串数组
【发布时间】:2013-03-30 01:48:04
【问题描述】:

我想问一个关于在Android 上将jsonArray 转换为StringArray 的问题。这是我从服务器获取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

[
    {"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"}
]

如何将我拥有的 jsonArray 转换为 StringArray,以便我可以像这样获得 StringArray:

array = {"IMG_20130403_140457.jpg","IMG_20130403_145006.jpg",........,"test.jpg"};

感谢您的帮助:)

【问题讨论】:

  • 为什么要这样做并浪费资源?
  • @Nezam,对不起,你是什么意思..?
  • 为什么要将显示的JSONArray 转换为ArrayListArray。有什么特殊用途吗?
  • 是的,在规范列表中它必须是 stringArray... :(
  • stackoverflow.com/a/55691694/470749 对我有帮助。 list.add(item.getAsString());

标签: java android json


【解决方案1】:

看看这个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"));
}

【讨论】:

  • 这个先转换成Array List,然后再转换成StringArray,谢谢给个思路...(y)
  • 你也可以使用 list.add(arr.getString(i)
  • 由于数组的长度是已知的,ArrayList 应该以明确的大小构造(例如new ArrayList&lt;String&gt;(arr.length())
【解决方案2】:

最简单正确的代码是:

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&lt;String&gt; 不是一个好主意,因为您知道数组的长度。 请注意,它在for 条件中使用arr.length,以避免在每个循环中调用方法,即array.length()

【讨论】:

    【解决方案3】:
    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;
    }
    

    【讨论】:

    • 仅代码的答案虽然可能是正确的,但很少能像解释原因的答案那样提供丰富的信息。考虑在您的帖子中添加一些 cmets 或解释。
    • 使用后检查“jsonArray”是否为空 - 是错误的,因为您可能会在检查之前获得 NPE。
    【解决方案4】:

    无耻的黑客:

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

    【讨论】:

    • 这是不安全的:[ { "name" : "},{" }, ... ]
    • 问题是,如果某个字符串包含json(如“},{”),它也会被拆分。
    【解决方案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()]);
    

    【讨论】:

      【解决方案6】:

      正在尝试相同的场景之一,但找到了一种不同且简单的解决方案将 JSONArray 转换为 List。

      import java.lang.reflect.Type;
      import com.google.gson.Gson;
      import com.google.gson.reflect.TypeToken;
      
      String jsonStringArray = "[\"JSON\",\"To\",\"Java\"]";                 
          
      //creating Gson instance to convert JSON array to Java array
                         
          Gson converter = new Gson();                  
          Type type = new TypeToken<List<String>>(){}.getType();
          List<String> list =  converter.fromJson(jsonStringArray, type );
      

      试一试

      【讨论】:

        【解决方案7】:

        代码如下:

        // 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);
                }
        

        【讨论】:

        • hmm,如果代码是用于动态数据的,我想知道......但谢谢你的回答...... :)
        • @andikurnia 您必须在s 中获取动态数据。如果对您有用,请接受答案。
        • 我认为如果 JSON 中有转义括号 ([),这将失败。
        • @Michael Munsey,如果键或值包含[,它不会失败,但结果不会包含[,请参阅s = s.replace("[", "").replace("]", "");。而且,我还提到了satisfies only with this particular string format。此代码应根据@andikurnia 的要求进行改进。
        【解决方案8】:

        你去吧:

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

        【讨论】:

        • 这很危险,因为数据中可能还有其他出现的“,”
        【解决方案9】:

        仅使用可移植的 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());
            }
        

        【讨论】:

          【解决方案10】:

          即用型方法:

          /**
          * 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;
          }
          

          【讨论】:

            【解决方案11】:

            您可能想查看JSONArray.toList(),它返回一个包含映射和列表的List,它们代表您的JSON 结构。因此,您可以像这样将它与 Java 流一起使用:

            JSONArray array = new JSONArray(jsonString);
            List<String> result = array.toList().stream()
                    .filter(Map.class::isInstance)
                    .map(Map.class::cast)
                    .map(o -> o.get("name"))
                    .filter(String.class::isInstance)
                    .map(String.class::cast)
                    .collect(Collectors.toList());
            

            这可能对更复杂的对象也很有用。

            或者,您可以只使用 IntStream 来遍历 JSONArray 中的所有项目并映射所有名称:

            JSONArray array = new JSONArray(jsonString);
            List<String> result = IntStream.range(0, array.length())
                    .mapToObj(array::getJSONObject)
                    .map(o -> o.getString("name"))
                    .collect(Collectors.toList());
            

            【讨论】:

              【解决方案12】:

              这是我的解决方案,您可能想要转换和合并多个数组:

              public static String[] multiJsonArrayToSingleStringArray(JSONArray... arrays) {
                  ArrayList<String> list=new ArrayList<>();
                  for (JSONArray array : arrays)
                      for (int i = 0; i < array.length(); i++)
                          list.add(array.optString(i));
              
                  return list.toArray(new String[list.size()]);
              }
              

              【讨论】:

                【解决方案13】:

                您可以将json数组输入到该函数中,以字符串数组的形式输出

                示例输入 - { “性别”:[“男性”,“女性”] }

                输出 - {“男性”,“女性”}

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

                【讨论】:

                • 虽然您可能已经解决了这个用户的问题,但纯代码的答案对以后遇到这个问题的用户没有多大帮助。请编辑您的答案以解释为什么您的代码解决了原始问题。
                • 答案不完整。如果您必须提供答案,请包括解释和额外的实用程序
                【解决方案14】:

                下面的代码将转换格式的JSON数组

                [{"version":"70.3.0;3"},{"version":"6R_16B000I_J4;3"},{"version":"46.3.0;3"},{"version":" 20.3.0;2"},{"version":"4.1.3;0"},{"version":"10.3.0;1"}]

                到字符串列表

                [70.3.0;3, 6R_16B000I_J4;3, 46.3.0;3, 20.3.0;2, 4.1.3;0, 10.3.0;1]

                代码

                ObjectMapper mapper = new ObjectMapper(); ArrayNode node = (ArrayNode)mapper.readTree(dataFromDb); data = node.findValuesAsText("version"); // "version" 是 JSON 中的节点

                并使用 com.fasterxml.jackson.databind.ObjectMapper

                【讨论】:

                  【解决方案15】:

                  答案有点晚,但这是我使用 Gson 得出的结论:

                  对于 jsonarray foo: [{"test": "bar"}, {"test": "bar2"}]

                  JsonArray foo = getJsonFromWherever();
                  String[] test = new String[foo.size()]
                  foo.forEach(x -> {test = ArrayUtils.add(test, x.get("test").getAsString());});
                  

                  【讨论】:

                    【解决方案16】:

                    我确实在此处发布了问题 here 的答案,尽管此处的回答有所帮助,但还不够。

                    所以,这是为了使用 jsonsimple 将 json 数组转换为 String[]

                    根据(了不起的)decode examples and docs,JSONArrays 是 java List,所以我们可以访问 List 方法。

                    从那里,是否可以将其转换为 String[] 并使用以下内容:

                        JSONObject assemblingTags = (JSONObject) obj.get("assembling-tags");
                        JSONArray aTagsList = (JSONArray) assemblingTags.get("list");
                        String[] tagsList = (String[]) aTagsList.stream().toArray(String[]::new);
                    

                    【讨论】:

                      【解决方案17】:

                      以下代码会将 JSON 数组转换为 List

                      例如;

                      import org.json.JSONArray
                      
                      String data = "YOUR_JSON_ARRAY_DATA";
                      JSONArray arr = new JSONArray(data);
                      List<String> list = arr.toList().stream().map(Object::toString).collect(Collectors.toList());
                      

                      【讨论】:

                      • 您应该清楚这与现有答案相比是什么(表面上看起来非常相似)。看起来你也没有使用data
                      猜你喜欢
                      • 2013-05-08
                      • 1970-01-01
                      • 2014-03-09
                      • 2015-02-16
                      • 1970-01-01
                      • 2023-03-21
                      • 2011-09-21
                      • 2012-04-28
                      • 2017-03-14
                      相关资源
                      最近更新 更多