![](/img/trans.png)
[英]Remove all elements except one from JSONArray of JSONObjects
[英]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.