Json 解析错误:无法将 java.lang.String 类型的值 <?xml 转换为 JSONArray



我是编程新手,我遇到了小问题,我正在尝试制作一个将使用 json 读取 flickr API 的应用程序,但我在描述中提到了错误,但我正在环顾四周,但没有一个解决方案有效,所以我来这里问

public class JSONPareser {
final String TAG = "JSONParser";
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) throws UnsupportedEncodingException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8);
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}

那是我的解析器类,这是我调用 JSON 对象的时候

public class getData extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait");
dialog.setCancelable(false);
dialog.show();
}
@Override
protected Void doInBackground(Void... params) {
String url = "https://api.flickr.com/services/feeds/photos_public.gne";
JSONPareser pareser = new JSONPareser();
String jsonStr = pareser.makeServiceCall(url);
if (jsonStr != null) {
try {
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
FlickrModel model = new FlickrModel();
model.setLink(obj.getString("link"));
model.setDescription(obj.getString("description"));
model.setTitle(obj.getString("title"));
model.setAuthor(obj.getString("author"));
model.setTags(obj.getString("tags"));
flickrList.add(model);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}

非常感谢

您的服务被视为返回 XML 而不是 JSON,请参阅标头

相关内容

最新更新