解析JSON字符串时面对JSONException
例外:
org.json.JSONException: Value anyType of type java.lang.String cannot be converted to JSONArray
代码段。
try {
androidHttpTransport.call(Soap_Action1, envelope);
SoapObject response = (SoapObject) envelope.getResponse();
String resp=response.toString();
Log.d("resp",response.toString());
// newwwwww
try {
JSONArray jsonArray = new JSONArray(resp);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
System.out.println(c.getInt("MST_BloodGroupID"));
System.out.println(c.getString("BloodGroup_Name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
response.toString()如下:
anyType的{架构= {anyType的元素= anyType的{的complexType = {anyType的选择= {anyType的元素= anyType的{的complexType = {anyType的序列= {anyType的元素= anyType的{}; 元素= anyType的{}; }; }; }; }; }; }; }; 的DiffGram = anyType的{DocumentElement = anyType的{表= anyType的{MST_BloodGroupID = 1; BloodGroup_Name = A +; };表= anyType的{MST_BloodGroupID = 2; BloodGroup_Name = A-; };表= anyType的{MST_BloodGroupID = 3; BloodGroup_Name = B +; };表= anyType的{MST_BloodGroupID = 4; BloodGroup_Name = B-; };表= anyType的{MST_BloodGroupID = 5; BloodGroup_Name = AB +; };表= anyType的{MST_BloodGroupID = 6; BloodGroup_Name = AB-; };表= anyType的{MST_BloodGroupID = 7; BloodGroup_Name = O +; };表= anyType的{MST_BloodGroupID = 8; BloodGroup_Name = O-; }; }; }; }
答案 0 :(得分:0)
私有类GetCategories扩展了AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching..");
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
System.out.println(catObj.getInt("id"));
System.out.println(catObj.getString("name"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
答案 1 :(得分:0)
您的response.toString()未返回有效JSON的数据。检查字符串是否有效JSON的快速方法是将其插入此站点:http://jsonviewer.stack.hu/ 如果它有效,您可以切换到查看器选项卡并可视化您的json,以确保您的代码正确检查与括号和花括号相关的JSONArrays和JSONObjects,我遇到的大多数错误解析JSON源于我只是误读了我的数据集。如果网站无效,网站会大声喊叫,就像你的数据一样。
我建议使用GSON库来创建JSON数据。将其导入项目后,您可以使用它:
Gson gson = new Gson();
SoapObject response = (SoapObject) envelope.getResponse();
String resp = gson.toJson(response);
除此之外,您从字符串数据创建JSON对象和数组的方法似乎是正确的。
答案 2 :(得分:0)
你不能将String转换为JSONArray,因为Strings不是Array它是一个JSONObject。
尝试将String转换为JSONObject,使用它的密钥从JSONObject获取数组。