2011-05-09 138 views
7

如何將一個JSONObject如"{hello1: hi, hello2: hey}"轉換爲"hello1: hi, hello2: hey"沒有這些括號{ }JSONObject到字符串Android

我知道有機會使用JSONObject.tostring,但我會得到一個帶括號的字符串。

謝謝大家。

回答

12

只要做一個子字符串或字符串替換。

子實例:

JSONObject a = new JSONObject("{hello1: hi, hello2: hey}"); 
String b = a.toString().substring(1, a.toString().length() - 1); 

字符串替換示例:

JSONObject a = new JSONObject("{hello1: hi, hello2: hey}"); 
String b = a.toString().replace("{", ""); 
String c = b.toString().replace("}", ""); 
+2

你需要拼出'長度'而不是'長度':) – user3241507 2014-05-15 16:26:27

2

假設你真正想要做的更精緻,比你的問題建議你可以做一些關於你將要使用的JSON的假設,你可以做如下的事情來獲得你想要的輸出格式。

JSONObject json = new JSONObject("{hello1: hi, hello2: hey}"); 

StringBuilder sb = new StringBuilder(); 
for(String k : json.keys()) { 
    sb.append(k); 
    sb.append(": "). 
    sb.append(json.getString(k)); 
    sb.append(", ") 
} 

// do something with sb.toString() 

然後,我可能已經讀了太多(在這種情況下@ ProgrammerXR的答案會做的伎倆)。