0

我正在从存储在应用程序中的 .json 文件中读取 json 响应。这就是我正在做的

private String readJSONResponse(){
        InputStream is = getResources().openRawResource(R.raw.json_data);
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } 
        catch(Exception e){

        }
        finally {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return writer.toString();
    }

每当我尝试读取文件时,都会以一些数据开头,例如11-11 11:30:57.789: I/System.out(3200): response that has been readed {\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf360 11-11 11:30:57.789: I/System.out(3200): {\fonttbl\f0\fmodern\fcharset0 Courier;} 11-11 11:30:57.789: I/System.out(3200): {\colortbl;\red255\green255\blue255;} 11-11 11:30:57.789: I/System.out(3200): \margl1440\margr1440\vieww16160\viewh10840\viewkind0 11-11 11:30:57.789: I/System.out(3200): \deftab720 11-11 11:30:57.789: I/System.out(3200): \pard\pardeftab720\ql\qnatural 11-11 11:30:57.799: I/System.out(3200): \f0\fs24 \cf0 \{"status": [\{"response": 13, //this is what is stored in my app

我如何摆脱这些数据和特殊字符,如“\”(请在回复之前检查它。)

4

2 回答 2

0
// try this
1. make "yourfilename.txt" file on your assert folder and put your json respone.
2. now run below code
private String readJSONResponse(){
        Writer writer=null;
        try{
            AssetManager assetManager = getAssets();
            InputStream is = assetManager.open("yourfilename.txt");
            writer = new StringWriter();
            char[] buffer = new char[1024];

            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return writer.toString();
}
于 2013-11-11T06:37:28.277 回答
0
InputStream is = getResources().openRawResource(R.raw.test);
BufferedReader br = new BufferedReader(new InputStreamReader(is));

StringBuilder sb = new StringBuilder();
String tempStr = null;

try {
    while ((tempStr = br.readLine()) != null) {
        sb.append(tempStr);
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Log.v("", "JSON DATA is " + sb.toString());

这对我有用。我将 test.json 文件放在原始文件夹中。确保您的 json 有效。您可以在http://jsonlint.com/上测试您的 json 文件

于 2013-11-11T06:23:05.607 回答