开发者

JSONObject to String Android

how can I convert a JSONObject like "{hello1: hi, hello2: hey}" to "hello1: hi, hello2: hey" without these brackets { 开发者_如何学Go} ?

I know that there is a opportunity to use JSONObject.tostring but then I'll get a string with the brackets.

Thanks all.


Just do a substring or string replace.

Pseudo substring Example:

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

Pseudo string replace Example:

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


Assuming that you actually want to do something more elaborate than your question suggests and you can make some assumptions about the JSON you'll be working with, you could do something like the following to get any output format you'd like.

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()

Then again, I might have read into this too much (in which case @ProgrammerXR's answer would do the trick).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜