2015-07-11 98 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(); 
    }