我是android的新手。这是我从服务中得到的Json有人请指点我如何在Session(共享首选项)中保存这个JSONResponse我已经在我的SessionManager类中定义了这个函数但是我无法保存它。 JSON:
{
"message": "Successfully Logged In.",
"auths": "KONG,KONG-Surveyor",
"user": {
"view_all_proposals": "0",
"role_id": "1",
"contact_no": "020 8547 4333 (x354)",
"date_modified": "2013-10-10 10:58:56",
"status": "ACTIVE",
"profit_margin_limit": "100",
"cash_code": "KHO",
"date_created": "2013-02-03 06:41:41",
"user_initials": "KHO",
"password": "f10343d1dc8d44c8935b356aa3f8aae2",
"id": "27",
"first_name": "Kong",
"username": "kong",
"is_admin": "0",
"address": "Technology Manager",
"email": "kong.hoang@mrfsgroup.com",
"proposal_review": "0",
"last_name": "Hoang",
"ldap_authentication": "1"
},
"status": true,
"apkStatus": true,
"apkFileDate": "2013-12-05 04:47:52",
"apkFile": "2_SurveyAppNew.apk"
}
这是我在SessionManger类中定义的函数:
public static void setUserObject(Context c, String userObject) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = pref.edit();
editor.putString("userObject", userObject);
editor.commit();
}
public static String getUserObject(Context ctx) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString("userObject", null);
return userObject;
}
答案 0 :(得分:5)
您可以简单地将整个JSONObject作为字符串。像这样:
String response = httpClient.execute(postMethod, resonseHandler);// your json parsing method
JSONObject jsonObject = new JSONObject(response);
setUserObject(context, jsonObject.toString(),"json_response");
然后你可以像:
那样回复它 JSONObject jsonObj = new JSONObject(getUserObject(context),"json_response");
将您的方法更改为:
public static void setUserObject(Context c, String userObject,String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, userObject);
editor.commit();
}
public static String getUserObject(Context ctx,String key) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(ctx);
String userObject = pref.getString(key, null);
return userObject;
}
书籍:
请查看Jaguar对this问题的回答。
好教程:
您可以找到最佳教程系列之一here。
视频Tutorial系列。
答案 1 :(得分:0)
JSONObject jObject_Main = new JSONObject(jsonStrng);
String jsonStr = jObject_Main.getString(jsonStringName);
JSONObject jsonObject = new JSONObject(jsonStr);
String message=jsonObject.getString("message");
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = pref.edit();
editor.putString("message", message);
editor.commit();
首先你应该将json字符串转换为json对象,并且基于jsonobject你可以使用json字符串。