从文本文件创建JSONObject

时间:2013-03-15 22:34:54

标签: java android json

我正在尝试读取文本文件并在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}]}

1 个答案:

答案 0 :(得分: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;
    }