2013-03-15 88 views
0

我試圖讀取文本文件並在Android應用程序中創建JSONObject,但在將文本文件讀入字符串後,我嘗試使用字符串構造JSONObject時出現JSONException 。從文本文件中創建JSONObject

這裏是我使用的代碼:

InputStream is = this.getResources().openRawResource(R.raw.quiz); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    String jsString = ""; 
    String line = null; 
    while((line = reader.readLine()) != null){ 
     jsString += line; 
    } 
    is.close(); 
    reader.close(); 

    try { 
     return new JSONObject(jsString); 
    } catch (JSONException e) { 

    } 
    return null; 

這裏是文本文件,我從,quiz.txt閱讀:

{"length":3,"questions":[{"questionText":"Is mayonaise an instrument?","answers":["Yes","no","no","no","no"],"correctAnswer":0},{"questionText":"10^2","answers":["1","10","100","1000","over 9000"],"correctAnswer":1},{"questionText":"Dogs Name?","answers":["Barky","Steve","Rex","Daisy","Wormy"],"correctAnswer":3}]} 
+0

是否有包含在異常中的消息('e.getMessage()')? – 2013-03-15 22:39:20

+0

您是否試圖將您的答案(數字)放在引號中? – Trinimon 2013-03-15 22:43:51

+0

我檢查了e.getMessage()的值,並能夠找出我的問題在哪裏。謝謝! – GammaGuy 2013-03-15 22:51:16

回答

0

嘗試使用這種方法來讀取文件內容到一個字符串。

public static String getJsonFromResource(int resource, Context context) { 

     InputStream inputStream = context.getResources().openRawResource(resource); 
     BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); 
     StringBuilder stringBuilder = new StringBuilder(); 
     String line; 
     String jsonString = null; 
     try { 
      while ((line = r.readLine()) != null) { 

       stringBuilder.append(line); 
      } 
      jsonString = stringBuilder.toString(); 
     } 
     catch (Exception e) { 
      Log.e("GetJsonFromResource", Log.getStackTraceString(e)); 
     } 
     return jsonString; 
    }