我正在使用JSONObject
来解析下载的内容。虽然解析器适用于大多数json,但它会在特定文件中抛出json的异常。
任何关于为什么抛出异常以及如何修复异常的建议都将非常感激。
代码:
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0], parseJson);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// The parsed result comes in here
// textView.setText(result);
}
private String downloadUrl(String URLString, boolean parseJSON) throws IOException { // when parsejson is false, xml will be parsed
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 50000;
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (useUserAuthentication) connection.setRequestProperty ("Authorization", "Basic TjN3czRwcDI0OnJld2R1Y0NvYVF1ZWFyZzk=");
else connection.setRequestProperty("Authorization", userToken);
connection.setDoInput(true);
connection.setRequestMethod(requestType);
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
if (postHashMap != null) {
connection.setDoOutput(true);
String query = getQuery(postHashMap);
int contentLength = query.getBytes("UTF-8").length;
connection.setFixedLengthStreamingMode(contentLength);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.close();
os.close();
}
// Starts the query
connection.connect();
int response = connection.getResponseCode();
Log.i(LOGTAG, "The response is: " + String.valueOf(response));
is = connection.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
// CREATE IMAGE FROM INPUT STREAM
//Bitmap bitmap = BitmapFactory.decodeStream(is);
//ImageView imageView = (ImageView) findViewById(R.id.image_view);
//imageView.setImageBitmap(bitmap);
if (parseJSON) {
try {
String length = String.valueOf(contentAsString.length());
Log.i(LOGTAG, "the length is " +length);
//contentAsString = "{\"string\":\"But during winter, it’s more important\"}";
//contentAsString.replace("’","'");
//contentAsString = "{\"user_id\":\"juan\"}";
JSONObject jsonObject = new JSONObject(contentAsString);
// New User
if (requestName.equals("NewUser")) {
String tempToken = jsonObject.getString("token");
String tempUserID = jsonObject.getString("user_id");
if (tempToken != null && tempToken.length() > 0) {
userToken = "Token " +tempToken;
Log.i(LOGTAG, "saving the token " +userToken);
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("UserToken", userToken);
editor.putString("UserID", tempUserID);
editor.commit();
// Request content
indexArticlesForCategories();
}
}
// Index articles
else if (requestName.equals("IndexArticlesForCategories")) {
Log.i(LOGTAG,"got here");
}
// User Profile
else if (requestName.equals("UserProfile")) {
Log.i(LOGTAG, "the user id is " +jsonObject.getString("user_id"));
}
}
catch (JSONException e) {
Log.i(LOGTAG, "json exception " +e.getMessage());
e.printStackTrace();
Log.getStackTraceString(e.getCause().getCause());
}
Log.i(LOGTAG, "the json data " + contentAsString);
}
return contentAsString;
// Makes sure that the InputStream is closed after the app is finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// convert input stream to text
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
// Reader reader = null;
// reader = new InputStreamReader(stream, "UTF-8");
// char[] buffer = new char[len];
// reader.read(buffer);
// return new String(buffer);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
堆栈跟踪(更新):
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.downloadUrl(WebServicesManager.java:248)
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:140)
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:126)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more
答案 0 :(得分:1)
我没有检查你的代码,但我总是使用以下代码片段,它一直有效。
<强> JSONParser.java 强>
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
并称之为:
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
有时json以数组节点而不是jSON对象节点开始。在这种情况下,您必须返回JSONArray
而不是JSONObject
答案 1 :(得分:0)
从我的角度来看,您必须先致电close()
至InputStream
和reader
,然后才能将回复作为:
stream.close();
reader.close();
return sb.toString();
如果你在运行上面的代码来分析问题时指定了什么样的错误会更好。
谢谢!
答案 2 :(得分:0)
请尝试以下方法: -
static InputStream is = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}} catch (Exception e) {
Log.e("Buffer Error", "Error Converting Result" + e.toString());
}
答案 3 :(得分:0)
发现了问题!
我回来了一个数组,不得不使用JSONArray而不是JSONObject