2016-10-27 20 views
0

JSONファイルからオブジェクトを読み込む際に問題があります。オブジェクトをJSONファイルに格納してオブジェクトの配列を返すことです。またはこれを行うためのJSONより優れたソリューションがありますか?ArrayListへのJSONファイルの読み込み

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_student_list); 


    TextView studentlistTextView =   (TextView)findViewById(R.id.studentlistTextView); 
    ArrayList<students> studentArray = loadJSONFromAsset(); 
    try { 
     studentlistTextView.setText(studentArray.get(0).getName()); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 

} 
public ArrayList<students> loadJSONFromAsset() { 
    ArrayList<students> studentArray = new ArrayList<>(); 
    String json = null; 
    try { 
     InputStream is = getAssets().open("jsonstudent"); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     json = new String(buffer, "UTF-8"); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
     return null; 
    } 
    try { 
     JSONObject obj = new JSONObject(json); 
     JSONArray m_jArry = obj.getJSONArray("students"); 

     for (int i = 0; i < m_jArry.length(); i++) { 
      JSONObject jo_inside = m_jArry.getJSONObject(i); 
      students student = new students(); 
      student.setName(jo_inside.getString("name")); 
      student.setLastname(jo_inside.getString("lastname")); 
      student.setNumber(jo_inside.getString("number")); 




      studentArray.add(student); 
     } 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    return studentArray; 
} 

} 

これは、あなたがJSONファイル内のオブジェクトを格納し、オブジェクトの配列を返すようにGsonと共有プリファレンスを使用することができ、私のJSONファイル

{ "student" : [ 
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" } 



]} 
+0

ことがある場合jsonを完了し、obj.getJSONArray( "students")をobj.getJSONArray( "student")に変更して試してみますか? – Raghavendra

+0

jsonファイルをsdcardに書き込む目的はありますか? – Radhey

答えて

1

です:

private final String PERSONAL_INFO = "personal_info"; 

public void putPersonalInfo(Profile info) { 
     Gson gson = new Gson(); 
     String json = gson.toJson(info); 
     getAppPreference().edit().putString(PERSONAL_INFO, json).commit(); 
    } 

    public Profile getPersonalInfo() { 
     Gson gson = new Gson(); 
     return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class); 
    } 
関連する問題