将 json 值密钥对解包到 SharedPreferences 的变量

少信息

我有一个 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();
 }
}

我认为这个问题经常被问到,但我尝试在 google 上搜索一个 anwser 并且很不清楚我应该如何将字符串格式化为变量。

我的应用程序的字符串输出如下所示:{"api_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJsdW1lbi1qd3QiLCJzdWIiOjEsImlhdCI6MTU0MTQyNjYxMiwiZXhwIjoxNTQxNTEzMDEyLCJuYW0iOiIxMjM0In0.7TR1ueOB-xqAkI6XgStUnn7HZxBTvxx3wzjKGHDnD4I","user_id":1}

有人告诉我,代码总是更好,中间有一个指针。

巴兹尔·巴蒂基

您不需要创建变量。由于响应是字符串,请保存 json 本身,另外我看到一个语法错误OnPostExecute()result参数是字符串,字符串没有调用方法,getJsonObject()因此您需要执行以下操作

JSONObject resultAsJsonObject=new  JSONObject(result);

与字符串不同,上述方式将让您将变量用作对象

我建议您将整个 json 保存到共享首选项中,这样您此时不需要转换它您可以创建模型并使用GSON这样您就不需要将其转换为 JSONObject 但是结果将是 json 结构, Gson 库会将你的 json 结果转换为 java 对象

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将值从 JSON 存储到变量

来自分类Dev

将JSON字典值存储到变量中

来自分类Dev

将JSON数据存储到变量中

来自分类Dev

将列表<Obj>存储到SharedPreferences

来自分类Dev

将`SharedPreferences` 数据从 Fragment 传递到 Activity

来自分类Dev

将 ArrayList 保存和检索到 SharedPreferences

来自分类Java

将ArrayList <CustomClass>存储到SharedPreferences中

来自分类Dev

使用 newtonsoft json 将值(变量)转换为 json 对象

来自分类Java

将JSON数组保存在SharedPreferences中可以吗?

来自分类Dev

SharedPreferences 和变量交换

来自分类Dev

提交到SharedPreferences变量

来自分类Dev

使用 SharedPreferences 保存变量

来自分类Dev

将JSON数据存储到Node中URL的变量中?

来自分类Dev

将json变量数据绑定到jquery的dropdownlist中

来自分类Dev

将 ajax 请求的 JSON 结果存储到 Easyautocomplete 的 javascript 变量

来自分类Dev

将变量传递到Python中为JSON的String vale

来自分类Dev

无法将变量从 .tf 文件传递到 .json 策略模板

来自分类Dev

将Javascript变量中的JSON传递到JQuery帖子中

来自分类Dev

如何使用AngularJS ngStorage将JSON变量存储到$ sessionStorage

来自分类Dev

将python / django变量作为JSON传递到JavaScript中?

来自分类Dev

将iOS GPS变量输入到JSON / oAUTH请求中

来自分类Dev

bash 将变量值存储到 JSON 文件中

来自分类Dev

如何将变量传递到JSON搜索循环中?

来自分类Dev

如何将两个json值解组到同一变量中?

来自分类Dev

无法将ruby变量插值到字符串url中以调用JSON API

来自分类Java

如何将多个Map <String,String>解包到Json

来自分类Dev

使用jq将JSON值提取到shell变量

来自分类Dev

如何将 Heroku 配置变量设置为 JSON 值?

来自分类Dev

将json配置值获取到Windows脚本变量中

Related 相关文章

  1. 1

    将值从 JSON 存储到变量

  2. 2

    将JSON字典值存储到变量中

  3. 3

    将JSON数据存储到变量中

  4. 4

    将列表<Obj>存储到SharedPreferences

  5. 5

    将`SharedPreferences` 数据从 Fragment 传递到 Activity

  6. 6

    将 ArrayList 保存和检索到 SharedPreferences

  7. 7

    将ArrayList <CustomClass>存储到SharedPreferences中

  8. 8

    使用 newtonsoft json 将值(变量)转换为 json 对象

  9. 9

    将JSON数组保存在SharedPreferences中可以吗?

  10. 10

    SharedPreferences 和变量交换

  11. 11

    提交到SharedPreferences变量

  12. 12

    使用 SharedPreferences 保存变量

  13. 13

    将JSON数据存储到Node中URL的变量中?

  14. 14

    将json变量数据绑定到jquery的dropdownlist中

  15. 15

    将 ajax 请求的 JSON 结果存储到 Easyautocomplete 的 javascript 变量

  16. 16

    将变量传递到Python中为JSON的String vale

  17. 17

    无法将变量从 .tf 文件传递到 .json 策略模板

  18. 18

    将Javascript变量中的JSON传递到JQuery帖子中

  19. 19

    如何使用AngularJS ngStorage将JSON变量存储到$ sessionStorage

  20. 20

    将python / django变量作为JSON传递到JavaScript中?

  21. 21

    将iOS GPS变量输入到JSON / oAUTH请求中

  22. 22

    bash 将变量值存储到 JSON 文件中

  23. 23

    如何将变量传递到JSON搜索循环中?

  24. 24

    如何将两个json值解组到同一变量中?

  25. 25

    无法将ruby变量插值到字符串url中以调用JSON API

  26. 26

    如何将多个Map <String,String>解包到Json

  27. 27

    使用jq将JSON值提取到shell变量

  28. 28

    如何将 Heroku 配置变量设置为 JSON 值?

  29. 29

    将json配置值获取到Windows脚本变量中

热门标签

归档