4

i building a json object that consists of nameValue pairs defined in a Hashmap

the issue i am having is when i invoke:

jsonObject.put(hashmap);

It adds the nameValue pairs like this:

name=value instead of name:value

Any thoughts?

Thanks

2

2 Answers 2

7

Use JSONObject constructor. DON"T CREATE YOUR OWN since you might miss some cases such when the value is an array.

JSONObject jsonObject = new JSONObject(hashMap);

This is actually a complete solution since it covers for corner cases such as where the value is an array. Thus, it will make it as JSONArray for you.

Sign up to request clarification or add additional context in comments.

1 Comment

Hate to dig up an old answer, but this does not work. The OP is asking for a conversion from HashMap<String, Object> to JSONObject. The constructor you mentioned only works with HashMap<String, String> as made clear here
6

Iterate through the HashMap and put to the jsonObject:

Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    jsonObject.put(pairs.getKey(), pairs.getValue() );
}

3 Comments

that did teh trick. Why doesnt jsonObject.put automatically handle it?
@jonney I am not sure, the documentation doesn't contain any put method with only one parameter... weird
There exists a built-in JSONObject constructor which covers for cases such as where the value is an array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.