2015-07-11 101 views
1

如何从我的“原始”文件夹内的本地JSON文件创建“JSONObject”。从本地JSON文件创建JSON对象

我在我的android应用程序项目的“原始”文件夹下有以下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中......问题是我不确定如何正确实现此代码,以便可以访问数据?如果你们中的任何一个人都能详细说明如何做到这一点,我会非常感激。

回答

0

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

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