繁体   English   中英

从 JSONArray 中删除所有引号

[英]Remove all the Quotes from JSONArray

JSONArray error = data.getJSONArray("error");

                for (int it=0; it<error.length(); it++){
             error.toString().replaceAll("\"", " ");
                    System.out.println(error);
                }           

我从已解析为 JSONArray 的 SOLR 链接获得了 JSON 响应。 在代码中,我试图从 JSONArray 中删除双引号。 但它没有发生。 谁能尽快帮我? 提前致谢。

我明白怎么了。 您没有打印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()

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

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

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

幸运的是,我们已经在使用一个为我们完成所有这些的库:) 只需使用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 对象中的值的其他方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM