我正在关注Micers回答store and retrieve a class object in shared preference
但是如何从JSOnObject
中检索回STring []我的课程是:
public class AppearExamState implements Serializable{
private static final long serialVersionUID = 1L;
Boolean flag = false;
int questionId;
int subjectId;
String[] storedAnswers;
public AppearExamState(int q, int subjId, String[] ans, boolean flg){
questionId = q;
subjectId = subjId;
storedAnswers = ans;
flag = flg;
} .......
.........getters and setters.....
.......
//-----------------------------------------------------------------
// Here I convert myObject to JsonObject
//-----------------------------------------------------------------
public JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
try {
obj.put("Qid", this.questionId);
obj.put("Stored_Ans", this.storedAnswers);// is this RIGHT??
obj.put("subj_id", this.subjectId);
obj.put("Flag", this.flag);
} catch (JSONException e) {
e.printStackTrace();
}
return obj;
}
现在,当我在sharepref中存储时,我跟着老鼠回答并做到了这一点:
//--------------------------------------------------------------------------------------
public void sendSharedPreference(ArrayList<AppearExamState> arrayl){
SharedPreferences mPrefs = this.getSharedPreferences("aimmds_state", 0);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Set<String> set= new HashSet<String>();
for (int i = 0; i < arrayl.size(); i++) {
set.add(arrayl.get(i).getJSONObject().toString());
}
prefsEditor.putStringSet("aimmds_state", set);
prefsEditor.commit();
}
//--------------------------------------------------------------------------------------
我被困在这里,不知道如何做到这一点
public ArrayList<AppearExamState> loadFromStorage(Context c) {
SharedPreferences mPrefs = c.getSharedPreferences("aimmds_state", 0);
ArrayList<AppearExamState> items = new ArrayList<AppearExamState>();
Set<String> set = mPrefs.getStringSet("aimmds_state", null);
for (String s : set) {
try {
JSONObject jsonObject = new JSONObject(s);
int Quesid = jsonObject.getInt("Qid");
int SubjId = jsonObject.getInt("subj_id");
Boolean flag = jsonObject.getBoolean("Flag");
String[] StoAnswer = ????? ;
AppearExamState myclass = new AppearExamState(Quesid, SubjId, StoAnswer, flag );
items.add(myclass);
} catch (JSONException e) {
e.printStackTrace();
}
}
return items;
}
答案 0 :(得分:1)
您不能将数组放到JSON中,但可以放置Collection
,它由JSONArray
(http://www.json.org/javadoc/org/json/JSONObject.html#put%28java.lang.String,%20java.util.Collection%29)表示。因此,将数组放到JSONObject
的正确方法是:
obj.put("Stored_Ans", new JSONArray(this.storedAnswers));
并得到:
JSONArray jsonArray = jsonObject.getJSONArray("Stored_Ans");
String[] StoAnswer = new String[jsonArray.length()];
for(i = 0; i < jsonArray.length(); i++){
StoAnswer[i] = jsonArray.getString(i);
}