13

how can I convert a JSONObject like "{hello1: hi, hello2: hey}" to "hello1: hi, hello2: hey" without these brackets { } ?

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

Thanks all.

Padma Kumar
20k17 gold badges77 silver badges131 bronze badges
asked May 9, 2011 at 7:17

2 Answers 2

17

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("}", "");
John Slavick
10.7k5 gold badges30 silver badges26 bronze badges
answered May 9, 2011 at 7:21
Sign up to request clarification or add additional context in comments.

1 Comment

you will need to spell length not lenght :)
3

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

answered May 9, 2011 at 7:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.