Android 应用中抛出 JSONException
JSONException being thrown in Android app
我有一个 iOS 应用程序和一个与 RESTFul 网络服务配合使用的 Android 应用程序。
当我对服务进行查询时,我得到一个 JSON 对象返回。
[
{
"id": 21,
"device_id": "xxxxxxxxxxx",
"api_key": "yyyyyyyyyy",
"customer_id": 28,
"created_at": "2014-12-08T11:21:01.517Z",
"updated_at": "2014-12-13T04:40:44.295Z",
"registered_at": "2014-12-08T11:22:49.960Z",
"install_date": "2014-11-18",
"serial_number": "1121113",
"last_communication_at": "2014-12-13T04:40:44.283Z",
"avg": null,
"min": null,
"max": null,
"usage_updated_at": null,
"usage_period_days": null,
"settings_change_upload_interval": 5,
"stats_upload_interval": 1440
}
]
iOS 检索和解析 JSON 信息没有问题。
在 Android 我正在尝试使用 JSONObject 来序列化我得到的响应(顺便说一句,我从 URL 请求中得到一个有效的状态代码 200 )
JSONObject myObject = new JSONObject(result);
但这会抛出一个异常,指出 JSON对象的格式不正确。
我对 API 的其他调用工作正常,所以是这个特定的 JSON 对象导致了问题。是不是因为其中一些值返回为 null 因为它们尚未在数据库中设置?
正如我所说,此数据包的 iOS JSON 序列化工作正常。
您正在尝试将数组解析为对象,这就是它给出异常的原因。另外,不要忘记在它周围放置一个 try-catch
方块。
使用这个
try
{
JSONArray myArr = new JSONArray(result);
JSONObject myObj = myArr.getJSONObject(0);
int id = myObj.getInt("id");
}
catch (JSONException e)
{
e.printStackTrace();
}
我有一个 iOS 应用程序和一个与 RESTFul 网络服务配合使用的 Android 应用程序。
当我对服务进行查询时,我得到一个 JSON 对象返回。
[
{
"id": 21,
"device_id": "xxxxxxxxxxx",
"api_key": "yyyyyyyyyy",
"customer_id": 28,
"created_at": "2014-12-08T11:21:01.517Z",
"updated_at": "2014-12-13T04:40:44.295Z",
"registered_at": "2014-12-08T11:22:49.960Z",
"install_date": "2014-11-18",
"serial_number": "1121113",
"last_communication_at": "2014-12-13T04:40:44.283Z",
"avg": null,
"min": null,
"max": null,
"usage_updated_at": null,
"usage_period_days": null,
"settings_change_upload_interval": 5,
"stats_upload_interval": 1440
}
]
iOS 检索和解析 JSON 信息没有问题。
在 Android 我正在尝试使用 JSONObject 来序列化我得到的响应(顺便说一句,我从 URL 请求中得到一个有效的状态代码 200 )
JSONObject myObject = new JSONObject(result);
但这会抛出一个异常,指出 JSON对象的格式不正确。
我对 API 的其他调用工作正常,所以是这个特定的 JSON 对象导致了问题。是不是因为其中一些值返回为 null 因为它们尚未在数据库中设置?
正如我所说,此数据包的 iOS JSON 序列化工作正常。
您正在尝试将数组解析为对象,这就是它给出异常的原因。另外,不要忘记在它周围放置一个 try-catch
方块。
使用这个
try
{
JSONArray myArr = new JSONArray(result);
JSONObject myObj = myArr.getJSONObject(0);
int id = myObj.getInt("id");
}
catch (JSONException e)
{
e.printStackTrace();
}