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
Android how to get int type in JSONObject
提问by Android-Droid
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
JSON 时遇到问题。我有一个整数,我需要在其中保存服务器返回给我的错误代码。问题是我必须在 中解析它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
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")
.
JSONObject
是等效于 json 文本响应的代码。这不是该响应的一个关键。您最有可能想要做的是读取服务器响应中包含的单个密钥。为此,请使用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()
.
如果您想编写一个JSONObject
而不是解析一个,请使用JSONObject.put()
.
int errorCode = 42;
JSONObject json = new JSONObject();
json.put("error_key", errorCode);
String jsonString = json.toString();
回答by dmon
回答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 构造函数。