java Android 如何在 JSONObject 中获取 int 类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7243607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:14:56  来源:igfitidea点击:

Android how to get int type in JSONObject

javaandroidjsoninteger

提问by Android-Droid

I have an issue with putting intin 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 JSONObjecttakes only Strings, not integers. Here is an example what I'm trying to do:

我在放入intJSON 时遇到问题。我有一个整数,我需要在其中保存服务器返回给我的错误代码。问题是我必须在 中解析它JSONObject,但JSONObject只需要字符串,而不是整数。这是我正在尝试做的一个例子:

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

Any suggestions how to solve that issue?

任何建议如何解决该问题?

回答by Houcine

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

你可以这样做 ; 当您尝试创建 json 对象时,请使用以下命令:

//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

回答by Houcine

JSONObjectis 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").

JSONObject是等效于 json 文本响应的代码。这不是该响应的一个关键。您最有可能想要做的是读取服务器响应中包含的单个密钥。为此,请使用JSONObject.getInt("key").

Sample:

样本:

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

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

如果您想编写一个JSONObject而不是解析一个,请使用JSONObject.put().

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

回答by dmon

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

创建一个新的JSONObject,然后在那个JSONObject调用上put("fieldName", intValue)。请参阅文档

回答by Georgy Gobozov

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

JSONObject 有一个公共 JSONObject(java.lang.Object bean) 构造函数。尝试使用代码字段创建 ErrorCode 对象并将其传递给 JSONObject 构造函数。