2015-02-23 56 views

回答

0

排球本身不能夠解析JSON,所以你需要使用GSON或...

1

你不需要凌空讀取來自資產目錄中的JSON文件。

在我的情況下,我從文件中加載一個Json數組到我的字符串「filePath」中。

final String filePath = readFromAsset(act, "json_to_load.json"); //act is my current activity 
    try { 
     JSONArray obj = new JSONArray(filePath); 
     for (int i = 0; i < obj.length(); i++) { 
      JSONObject jo = obj.getJSONObject(i); 
      // do stuff 

     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 

在我的utils的文件:

private static String readFromAsset(Activity act, String fileName) 
{ 
    String text = ""; 
    try { 
     InputStream is = act.getAssets().open(fileName); 

     int size = is.available(); 

     // Read the entire asset into a local byte buffer. 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     text = new String(buffer); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return text; 
} 

爲了能夠使用它你必須import the package "org.json;"

希望它有幫助!

相關問題