2013-07-23 64 views
2

我正在使用JSONObject解析下載的內容。儘管解析器對大多數json都有效,但它在特定文件中爲json拋出異常。JSONObject解析錯誤

任何有關爲什麼拋出異常以及如何修復的建議都將不勝感激。

代碼:

@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

張貼exeption /堆棧跟蹤,請 –

+0

有什麼異常的內容? – CodingIntrigue

+0

BufferedReader streamReader = new BufferedReader(new InputStreamReader(stream,「UTF-8」));可能工作,很難說,沒有stracktrace。 – user634545

回答

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

+0

這是你使用JSONArray的最後一條評論,它使我走上了正確的道路。謝謝! – RunLoop

+0

不客氣!接受我的答案,如果它解決了你的問題! –

0

從我的角度來看,你必須在返回的響應,之前調用close()InputStreamreader

stream.close(); 
reader.close(); 
return sb.toString(); 

這將是你更好指定運行上述代碼分析問題時得到的錯誤類型。

謝謝!

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()); 
} 
0

發現問題!

我正在回一個數組,只好用JSONArray而非JSONObject的