2015-07-11 63 views

回答

0

尝试这种方式

public static String AssetJSONFile (String filename, Context context) throws IOException { 
    AssetManager manager = context.getAssets(); 
    InputStream file = manager.open(filename); 
    byte[] formArray = new byte[file.available()]; 
    file.read(formArray); 
    file.close(); 

    return new String(formArray); 
    }   

    public void getJson() 
    { 
    ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>(); 
    Context context = null; 
    HashMap<String, String> hashMap; 

    try { 
     String jsonLocation = AssetJSONFile("yourjson.json", context); 
     String id; 
     String question; 

     JSONArray JsonArray = jsonObject.getJSONArray("arjuna"); 
     { 
       for (int k = 0; k < JsonArray.length(); k++) 
      { 
       JSONObject jsonObject = JsonArray.getJSONObject(k); 

       id= JSONObject.getString("id"); 
       question= JSONObject.getString("question"); 

       hashMap = new HashMap<String, String>(); 
       hashMap.put("id", id); 
       hashMap.put("question", question); 

       formList.add(hashMap); 
      } 
     } 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
} 
0
try { 
      InputStream inputStream = getAssets().open("json.txt"); 
      String s = convertStreamToString(inputStream); 
      JSONObject object = new JSONObject(); 
      JSONArray jsonArray = object.getJSONArray("arjuna"); 
      HashMap hashMap = null; 
      ArrayList<HashMap> arrayList = new ArrayList<HashMap>(); 
      for (int i = 0; i < jsonArray.length(); i++) { 
       JSONObject obj = (JSONObject) jsonArray.get(i); 
       int id = obj.getInt("id"); 
       String question = obj.getString("question"); 
       hashMap = new HashMap(); 
       hashMap.put("id", id); 
       hashMap.put("question", question); 
       arrayList.add(hashMap); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

private String convertStreamToString(InputStream is) { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
     StringBuilder sb = new StringBuilder(); 

     String line = null; 
     try { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line).append('\n'); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    }