简体   繁体   English

JSONObject到String Android

[英]JSONObject to String Android

how can I convert a JSONObject like "{hello1: hi, hello2: hey}" to "hello1: hi, hello2: hey" without these brackets { } ? 我怎样才能将像"{hello1: hi, hello2: hey}"这样的JSONObject转换为"hello1: hi, hello2: hey"而没有这些括号{ }

I know that there is a opportunity to use JSONObject.tostring but then I'll get a string with the brackets. 我知道有机会使用JSONObject.tostring然后我会得到一个带括号的字符串。

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. 假设您实际上想要做一些比您的问题建议更精细的事情,并且您可以对您将要使用的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()

Then again, I might have read into this too much (in which case @ProgrammerXR's answer would do the trick). 再说一遍,我可能已经读过太多了(在这种情况下,@ ProgrammerXR的答案可以解决这个问题)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM