Android how to get int type in JSONObject

15,044

Solution 1

you can do this ; when you try to create your json object , use this :

//method 1
String myJson = " {errorCode:"+errorCode+"}";
ErrorCode = new JSONObject(myJson);

//method 2
ErrorCode = new JSONObject();
ErrorCode.put("errorCode", errorCode);// jsonObject.put(String key,Object value);

and then when you try to parse it , you can use :

json.getInt(String key); // in this case, the key is : errorCode

Solution 2

Create a new JSONObject, then on that JSONObject call put("fieldName", intValue). See docs.

Solution 3

JSONObject have a public JSONObject(java.lang.Object bean) constructor. Try to create ErrorCode object with code field and pass it to JSONObject constructor.

Share:
15,044
Android-Droid
Author by

Android-Droid

Android developer.

Updated on June 17, 2022

Comments

  • Android-Droid
    Android-Droid almost 2 years

    I have an issue with putting int in JSON. I have an integer where I need to save the error code which server returns me. The problem is that I have to parse it in JSONObject, but JSONObject takes only Strings, not integers. Here is an example what I'm trying to do:

    int errorCode;
    JSONObject ErrorCode;
    ErrorCode = new JSONObject(errorCode);
    

    Any suggestions how to solve that issue?