如何解析资产文件夹中的json到listview?

时间:2017-06-01 12:59:37

标签: android json android-assets

我想将资产文件夹中文件中的json文本和图像解析为listview。请清楚解释因为我是android中的biginner。给我所有文件的完整代码。非常感谢你。

2 个答案:

答案 0 :(得分:0)

只需打开资产文件夹中的文件,就像这样

    StringBuilder buf=new StringBuilder();
    InputStream json;
    try {
        json = context.getAssets().open("YOUR_FILE_NAME.txt");
    BufferedReader in=
        new BufferedReader(new InputStreamReader(json, "UTF-8"));
    String str;

    while ((str=in.readLine()) != null) {
      buf.append(str);
    }
    }
    catch (IOException e1) {
        e1.printStackTrace();
    }
    result1 = buf.toString();

result1将拥有您文件中的完整json

然后使用这个名为Gson的库来解析json ...

以下是Json parsing through Gson

的教程

答案 1 :(得分:0)

也许代码可以帮到你。

public class MainActivity extends Activity {


private ListView listView;

private void log(String msg) {
    Log.d("DNB", this.getClass().getName() + ">>" + msg);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.listView = new ListView(this);


    String jsonData = loadJsonFromAsset();
    String[] items = parseJson(jsonData);

    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);

    listView.setAdapter(adapter);
    setContentView(listView);
    log("json from asset: " + jsonData);

}

private String[] parseJson(String jsonData) {

    String[] items = new String[0];
    if (jsonData != null) {
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            if (jsonArray != null) {
                items = new String[jsonArray.length()];
                for (int i = 0; i < items.length; i++) {
                    items[i] = jsonArray.get(i).toString();
                }
            }
        } catch (JSONException e) {
            log("err--" + e.toString());
        }
    }


    return items;
}


private String loadJsonFromAsset() {
    InputStream stream;
    try {
        stream = getBaseContext().getAssets().open("json_list.txt");
        if (stream != null) {
            int size = stream.available();
            byte[] buffer = new byte[size];
            stream.read(buffer);
            stream.close();

            if (buffer != null) {
                return new String(buffer);
            }
        }
    } catch (IOException e1) {
        log("err--" + e1.toString());
    }
    return "";
}

资产中的json文件

["item line 1","item line 2","item line 3"]