从JSONArray中删除所有引号

时间:2018-02-21 03:19:17

标签: java arrays json solr

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 个答案:

答案 0 :(得分:1)

我看错了。您没有打印replaceAll来电的结果。要从json数组输出中删除所有引号,请尝试此操作。

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

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

org.json.JSONArray文档

答案 1 :(得分:0)

看起来你正在尝试打印一个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对象中的值的其他方法。

相关问题