Kamal Oberoi
Kamal Oberoi

Reputation: 165

JSONObject.put(string,string) not working

String value = myInput.getText().toString();

I want to put string value into JSONObject.put("STRING",value) method but it's not working..

See the attached screen shot and tell how to resolve this.

enter image description here

Upvotes: 3

Views: 14807

Answers (3)

Sujay
Sujay

Reputation: 3455

You should wrap the code inside try-catch

try {
    JSONObject j = new JSONObject(data);
} catch (JSONException e) {        
    e.printStackTrace();
}

Why try-catch is compulsary??

There are 2 kinds of exceptions: Checked and Unchecked.

  1. Checked exception can be considered one that is found by the compiler, and the compiler knows that it has a chance to occur, so you need to catch or throw it.

  2. Unchecked exception is a Runtime Exception which means these are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.

JSONException is a type of Checked exception. Checked exceptions needs to be handled at compile time itself.

new JSONObject(data) will throw JSONException if the parse fails or doesn't yield a JSONObject. So it is recommended to wrap it inside a try-catch block at compile time itself & the underlying IDE will show an error message for the same.

Upvotes: 4

Nitesh Pareek
Nitesh Pareek

Reputation: 362

Put your code in try.. catch block because may be Exception occur

 try{
         JSONObject params = new JSONObject(data);  
    }
 catch (JSONException e)
    {
        e.printStackTrace();
    }

Upvotes: 2

Sathish Kumar J
Sathish Kumar J

Reputation: 4345

Add try.. catch

String data = "";
String val = "hello";
            try {
                JSONObject j = new JSONObject(data);
                j.put("VAL", val);
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

Upvotes: 5

Related Questions