0

我正在尝试在 Android 应用程序中读取文本文件并创建 JSONObject,但是在将文本文件读入字符串后,当我尝试使用该字符串构造 JSONObject 时抛出 JSONException。

这是我正在使用的代码:

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}]}
4

1 回答 1

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;
    }
于 2013-03-15T22:55:51.060 回答