开发者

Android how to get int type in JSONObject

开发者 https://www.devze.com 2023-04-01 18:50 出处:网络
I have an issue with putting int in JSON. I have an开发者_JAVA百科 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 JSONOb

I have an issue with putting int in JSON. I have an开发者_JAVA百科 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?


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


JSONObject is the code equivalent to a json text-response. It's not a single key of that response. What you most likely want to do is read a single key thats contained in the servers response. For that, use JSONObject.getInt("key").

Sample:

int errorCode;
JSONObject json = new JSONObject(serverResponseString);
errorCode = json.getInt("error_key");

If you want to compose a JSONObject instead of parsing one, use JSONObject.put().

int errorCode = 42;
JSONObject json = new JSONObject();
json.put("error_key", errorCode);
String jsonString = json.toString();


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消