我使用mvc 4 web api获取JSONArray
并在Android应用程序中使用它但发生此错误:
of type java.lang.String cannot be converted to JSONArray
这是JSON:
[{
"FileType": {
"FileTypeId": 1,
"Name": "Estate",
"CodeLength": 5
},
"FileId": 2,
"FileTypeId": 1,
"FileNumber": "12345"
}, {
"FileType": {
"FileTypeId": 1,
"Name": "Estate",
"CodeLength": 5
},
"FileId": 3,
"FileTypeId": 1,
"FileNumber": "12345"
}]
这是我的代码:
@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jArray = new JSONArray(jsonStr); //<=== Error is Here
JSONArray Files = null;
// Getting JSON Array node
Files = jArray;
// looping through All Files
for (int i = 0; i < Files.length(); i++) {
JSONObject c = Files.getJSONObject(i);
String FileNumber = c.getString(TAG_FileNumber);
// FileType node is JSON Object
JSONObject FileType = c.getJSONObject(TAG_FileType);
String Name = FileType.getString(TAG_FileType_Name);
// tmp hashmap for single contact
HashMap<String, String> file = new HashMap<String, String>();
// adding each child node to HashMap key => value
file.put(TAG_FileNumber, FileNumber);
file.put(TAG_FileType_Name, Name);
// adding file to file list
FileList.add(file);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
答案 0 :(得分:0)
也许我不是帮助你的最好的人,因为你在特定领域缺乏知识,你会回答:但
我在这里查了一下:http://www.json.org/javadoc/org/json/JSONArray.html#JSONArray(java.lang.String)
并且其中一个构造函数将String作为参数,它表示:
参数:source - 以[(左括号)开头并以](右括号)开头的字符串。
尝试输入该格式的字符串!
答案 1 :(得分:0)
将这些行添加到json字符串中作为
{
"array":
// your json
}
并更改此行
JSONArray jArray = new JSONArray(jsonStr);
到
JSONObject jObj = new JSONObject(jsonStr);
JSONArray jArray= jObj.getJSONArray("array");