从本地JSON文件创建JSON对象

时间:2015-07-11 20:38:30

标签: android json inputstream

如何从“raw”文件夹中的本地JSON文件创建“JSONObject”。

我的android app项目的“raw”文件夹下有以下JSON文件。该文件名为“app_currencies.json”。我需要在我的课程中将此文件中包含的信息作为对象。以下是文件内容:

{
  "EUR": { "currencyname":"Euro", "symbol":"EUR=X", "asset":"_European Union.png"},
  "HTG": { "currencyname":"Haitian Gourde", "symbol":"HTG=X", "asset":"ht.png"},
  "WST": { "currencyname":"Samoan Tala", "symbol":"WST=X", "asset":"ws.png"},
  "GBP": { "currencyname":"British Pound", "symbol":"GBP=X", "asset":"gb.png"}
}

我认为我需要的是使用以下内容:

//Get data from Json file and make it available through a JSONObject   
InputStream inputStream = getResources().openRawResource(R.raw.app_currencies.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JSONObject jObject = new JSONObject;
我需要

jObject 。我想我需要一个InputStream,ByteArrayOutputStream以便我可以将它存储到JSONObject中......问题是我不确定如何正确实现这段代码以便我可以访问数据?如果你们中的任何一个人能够详细说明如何做到这一点,我将非常感激。

1 个答案:

答案 0 :(得分:0)

以下代码将json文件读入Json数组。看看它是否有帮助。请注意,该文件存储在Assets中

    BufferedReader reader = null;
    try {
        // open and read the file into a StringBuilder
        InputStream in =mContext.getAssets().open(mFilename);
        reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder jsonString = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            // line breaks are omitted and irrelevant
            jsonString.append(line);
        }
        // parse the JSON using JSONTokener
        JSONArray array = (JSONArray) new JSONTokener(jsonString.toString()).nextValue();

        // do something here if needed from JSONObjects
        for (int i = 0; i < array.length(); i++) {
        }

    } catch (FileNotFoundException e) {
        // we will ignore this one, since it happens when we start fresh
    } finally {
        if (reader != null)
            reader.close();
    }
相关问题