代码之家  ›  专栏  ›  技术社区  ›  user3222718

删除JSONArray中的所有引号

  •  -2
  • user3222718  · 技术社区  · 8 年前
    JSONArray error = data.getJSONArray("error");
    
                    for (int it=0; it<error.length(); it++){
                 error.toString().replaceAll("\"", " ");
                        System.out.println(error);
                    }           
    

    我从SOLR链接获得了一个JSON响应,该链接已被解析为JSONArray。在代码中,我试图从JSONArray中删除双引号。但这并没有发生。有谁能尽早帮助我吗?提前谢谢。

    2 回复  |  直到 8 年前
        1
  •  1
  •   dhoodlum    8 年前

    我知道怎么了。您没有打印来自的结果 replaceAll 呼叫要从json数组输出中删除所有引号,请尝试以下操作。

    JSONArray error = data.getJSONArray("error");
    System.out.println(error.toString().replaceAll("\"", " "));
    

    请注意,这还将删除数组值中的任何引号,这可能不是您想要的。例如,输出 ["cool says \"meow\"","stuff"] 可能是 [ cool says \ meow\ , stuff ] . 如果只需要字符串值,我建议查看 org.json.JSONArray 的文档 JSONArray::get(int) 和 JSONArray::length()

        2
  •  0
  •   dhoodlum    8 年前

    看起来您正在尝试打印json字符串数组。如果替换所有引号,它还将替换字符串中的引号,并扭曲编码的值。如果有人这样对我,我不会很高兴:)。例如,看看这个json。

    [
      "hello",
      "cat says \"meow\"",
      "dog says \"bark\"",
      "the temperature is 15\u00B0"
    ]
    

    不仅引号会丢失,而且度的特殊unicode字符可能看起来不正确( 15° ). 要以原始形式返回值,需要实现整个 json spec ! 这是很多工作,可能不是你想做的。我以前做过,这不容易。

    幸运的是,我们已经在使用一个库来为我们完成所有这些:)只需使用 org.json 包裹它拥有正确编码和解码值所需的一切。你不认为你必须自己做所有这些分析,是吗?要以原始形式打印字符串,可以这样做。

    /** use these imports
     *
     * import org.json.JSONArray;
     * import org.json.JSONObject;
     * import org.json.JSONException;
     **/
    JSONArray ja = new JSONArray();
    
    // add some strings to array
    ja.put("hello");
    ja.put("cat says \"meow\"");
    ja.put("the temperature is 15\u00B0");
    
    // add an int
    ja.put(1);
    
    // add an object
    JSONObject jo = new JSONObject();
    jo.put("cool", "cool");
    ja.put(jo);
    
    // loop and print only strings
    for (int i = 0; i < ja.length(); ++i) {
        try {
            // ignore null values
            if (!ja.isNull(i)) {
                System.out.println(ja.getString(i));
            }
        } catch (JSONException e) {
            // not a string
            // try ja.getBoolean
            // try ja.getDouble
            // try ja.getInt
            // try ja.getJSONArray
            // try ja.getJSONObject
            // try ja.getLong
        }
    }
    

    要与原始代码一起使用,只需替换 ja 使用您自己的变量。注意,在catch子句中,我添加了一些注释,显示了可以用来读取已解析json对象中的值的其他方法。