从文本文件创建JSONObject [英] Creating JSONObject from text file

查看:143
本文介绍了从文本文件创建JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am attempting to read a text file and create a JSONObject in an Android application, but after reading the text file into a string, I get a JSONException thrown when I try to construct a JSONObject using the string.

这是我正在使用的代码:

Here is the code I am using:

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:

Here is the text file I am reading from, 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}]}

推荐答案

尝试使用此方法将文件内容读取为字符串.

Try using this method to read the file contents into a string.

 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;
    }

这篇关于从文本文件创建JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆