Kevin
Kevin

Reputation: 23634

Unhandled exception type JSONException

JSONObject login = new JSONObject();
login.put("Key1", "Value1");

I was just trying to create a simple JSON Object with key and value pairs. I get this exception "Unhandled exception type JSONException".

Map<String,String> map = new HashMap<String,String>
map.put("key1", "value1");

Are they both equivalent way of creating an object with key, value pair. Which is the preferred way when creating an object which needs to send to a service.

Upvotes: 6

Views: 29328

Answers (2)

Simon Dorociak
Simon Dorociak

Reputation: 33505

Unhandled exception type JSONException

You need to wrap your code into try-catch block. This is your warning.

JSONObject login = new JSONObject();
    try {
        login.put("Key1", "Value1");
    } 
    catch (JSONException e) {... }

Are they both equivalent way of creating an object with key, value pair. Which is the preferred way when creating an object which needs to send to a service.

JSONObject.put() throws JSONException and Map.put() not.

Both are working as key-value pairs but they are different.

JSON is specific lightweight format usually used for data interchange and if you create it you can easily pass its string representation via network.

With Map as data structure it's not possible(directly converting to string) or in the other words you have to go though KeySet() in Map and for each key store key with its value to String(with StringBuilder for example) if you want to achieve almost same thing as with JSON.

So if you want to pass data between "different machines" via network, JSON is directly designated for it.

Upvotes: 21

Ezhil V
Ezhil V

Reputation: 882

Go for JSONObject:

  • When you want to create JSON or manipulate it

  • If the service you are passing the data accepts JSONObject

    Go for Collections

  • if a particular datastructure suits you

  • If the service you are passing the data accepts a Collection object

Upvotes: 1

Related Questions