Flutter中如何将登录API的JSON响应分别保存至SharedPreferences
Alright, let's break down how to save every field from your login API response into SharedPreferences. I'll cover both manual JSON parsing and using Gson (a popular library for JSON handling) since both approaches are common in Android development.
Step 1: Get a SharedPreferences Instance
First, you need access to SharedPreferences using your app's Context. For example, in an Activity:
SharedPreferences loginPrefs = getSharedPreferences("LoginPreferences", Context.MODE_PRIVATE); SharedPreferences.Editor editor = loginPrefs.edit();
"LoginPreferences" is a custom filename for your preferences file—feel free to name it something that fits your app. MODE_PRIVATE ensures only your app can access these stored values.
Option 1: Manual JSON Parsing
If you don't want to use an external library, parse the JSON manually with JSONObject:
// Assume your API response is stored in a String variable called responseString try { // Parse the top-level response JSONObject responseObj = new JSONObject(responseString); int code = responseObj.getInt("code"); String status = responseObj.getString("status"); // Parse the nested "data" object JSONObject dataObj = responseObj.getJSONObject("data"); boolean isNewUser = dataObj.getBoolean("isNewUser"); String customerUUID = dataObj.getString("customerUUID"); String userName = dataObj.getString("userName"); // Parse the nested "token" object inside "data" JSONObject tokenObj = dataObj.getJSONObject("token"); String accessToken = tokenObj.getString("Accesstoken"); String refreshToken = tokenObj.getString("Refreshtoken"); long expirationPeriod = tokenObj.getLong("expirationperiod"); // Save all fields to SharedPreferences editor.putInt("login_code", code); editor.putString("login_status", status); editor.putBoolean("is_new_user", isNewUser); editor.putString("customer_uuid", customerUUID); editor.putString("user_name", userName); editor.putString("access_token", accessToken); editor.putString("refresh_token", refreshToken); editor.putLong("token_expiration", expirationPeriod); // Commit changes (apply() is asynchronous and non-blocking, preferred for most cases) editor.apply(); } catch (JSONException e) { e.printStackTrace(); // Handle parsing errors here, like showing an error message to the user }
Option 2: Using Gson for Simplified Parsing
If you're already using Gson (or want to reduce boilerplate), first create model classes that mirror your JSON structure:
public class LoginResponse { private int code; private String status; private Data data; // Getters and setters public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Data getData() { return data; } public void setData(Data data) { this.data = data; } public static class Data { private boolean isNewUser; private String customerUUID; private String userName; private Token token; // Getters and setters public boolean isNewUser() { return isNewUser; } public void setNewUser(boolean newUser) { isNewUser = newUser; } public String getCustomerUUID() { return customerUUID; } public void setCustomerUUID(String customerUUID) { this.customerUUID = customerUUID; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public Token getToken() { return token; } public void setToken(Token token) { this.token = token; } public static class Token { private String Accesstoken; private String Refreshtoken; private long expirationperiod; // Getters and setters public String getAccesstoken() { return Accesstoken; } public void setAccesstoken(String accesstoken) { Accesstoken = accesstoken; } public String getRefreshtoken() { return Refreshtoken; } public void setRefreshtoken(String refreshtoken) { Refreshtoken = refreshtoken; } public long getExpirationperiod() { return expirationperiod; } public void setExpirationperiod(long expirationperiod) { this.expirationperiod = expirationperiod; } } } }
Then parse the response and save the fields:
// Convert the response string to your LoginResponse object Gson gson = new Gson(); LoginResponse loginResponse = gson.fromJson(responseString, LoginResponse.class); // Save each field to SharedPreferences editor.putInt("login_code", loginResponse.getCode()); editor.putString("login_status", loginResponse.getStatus()); editor.putBoolean("is_new_user", loginResponse.getData().isNewUser()); editor.putString("customer_uuid", loginResponse.getData().getCustomerUUID()); editor.putString("user_name", loginResponse.getData().getUserName()); editor.putString("access_token", loginResponse.getData().getToken().getAccesstoken()); editor.putString("refresh_token", loginResponse.getData().getToken().getRefreshtoken()); editor.putLong("token_expiration", loginResponse.getData().getToken().getExpirationperiod()); editor.apply();
Key Tips
- Consistent Key Names: Use clear, predictable key names (like
"access_token") so you can easily retrieve these values later. - Context Access: If working outside an Activity (e.g., a helper class), pass a valid Context to
getSharedPreferences(). - Error Handling: Always wrap JSON parsing in a try-catch block to handle invalid responses gracefully.
- apply() vs commit():
apply()is asynchronous and won't block the main thread, so it's the better choice for most scenarios.commit()returns a success boolean but runs synchronously.
内容的提问来源于stack exchange,提问作者Niroop Nife

