Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exception type JSONException

Tags:

java

android

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.

like image 771
Kevin Avatar asked Mar 29 '13 11:03

Kevin


2 Answers

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.

like image 135
Simon Dorociak Avatar answered Oct 26 '22 01:10

Simon Dorociak


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

like image 29
Ezhil V Avatar answered Oct 25 '22 23:10

Ezhil V