我有一个 json,我需要一些帮助来格式化它,以便我可以将值保存在 SharedPreferences 中,这是困扰我的代码。
public class MainActivity extends AppCompatActivity {
public static final String EXTRA_MESSAGE = "com.example.cumaskp.mercfood";
private SharedPreferences mPreferences;
private SharedPreferences.Editor mEditor;
EditText username;
EditText password;
Button loginbutton;
Button signupBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mEditor = mPreferences.edit();
username = (EditText) findViewById(R.id.usernameEditText);
password = (EditText) findViewById(R.id.mailEditText);
signupBtn = (Button) findViewById(R.id.signUpButton);
loginbutton = (Button) findViewById(R.id.loginBtn);
signupBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
Intent myIntent = new Intent(MainActivity.this, getData.class);
MainActivity.this.startActivity(myIntent);
}
});
loginbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new SendPostRequest().execute();
}
});
}
public class SendPostRequest extends AsyncTask<String, Void, String> {
protected void onPreExecute(){}
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://192.168.111.42/api/login"); //TODO here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", username.getText().toString());
postDataParams.put("password", password.getText().toString());
Log.e("params",postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return new String("false : "+responseCode);
}
}
catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
// it is right here the problem is! -----------------------------------------------------------------------------
try {
for (int i = 0; i < result.length(); i++) {
JSONObject jsonObj = result.getJSONObject(i);
String k = jsonObj.keys().next();
Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
mEditor.putString("token",result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
String token = mPreferences.getString("key", "default");
Log.d("myTag", "onPostExecute: "+ token);
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
我认为这个问题经常被问到,但我尝试在谷歌上搜索答案,但非常不清楚我应该如何将字符串格式化为变量。
我的应用程序的字符串输出如下所示:{"api_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEsImlhdCI6MTU0MTQyNjYxMiwiZXhwIjoxNTQxNTEzMDEy LCJuYW0iOiIxMjM0In0.7TR1ueOB-xqAkI6XgStUnn7HZxBTvxx3wzjKGHDnD4I","user_id":1}
有人告诉我,代码越多越好,中间有一个指针。
最佳答案
您不需要创建变量。
由于响应是字符串,
保存 json 本身,
我还看到一个语法错误 OnPostExecute()
result
参数是字符串,而字符串没有名为 getJsonObject()
的方法,所以你需要执行以下操作
JSONObject resultAsJsonObject=new JSONObject(result);
上面的方法可以让你使用变量作为对象,而不是字符串
我建议您将整个 json 保存到共享首选项中,这样您此时就不需要转换它 您可以创建一个模型并使用 GSON这样你就不需要将其转换为 JSONObject,但结果将是 json 结构,Gson 库会将你的 json 结果转换为 java 对象
关于java - 将 json 值 key 对解压为 SharedPreferences 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53155991/