2011-05-09 64 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的答案会做的伎俩)。