【问题标题】:How to save the value of json response in shared preference?如何在共享首选项中保存 json 响应的值?
【发布时间】:2016-02-04 06:35:59
【问题描述】:

我必须点击 json 服务,如果响应正确,我必须将用户值保存在共享首选项中以供将来使用。我该怎么做?

我的网址是: http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id={aff_id}

变量将由 sdk 用户传递。在上面的网址中,我的变量是 - id: 4 和 public_key: 9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G

我创建了一个类并声明了一个静态方法。在静态方法中,我必须进行解析并将变量保存在共享首选项中。

public class InitializeSDK {
   public static void init(final Context ctx, int id, String public_key){
     new AsyncTask<Void, Void, Void>() {

        protected void onPreExecute() {
            super.onPreExecute();
        }

        protected Void doInBackground(Void... unused) {

            return null;

        }

        protected void onPostExecute(Void unused) {

        }

     }.execute();
  }

}

请告诉我如何解析它以获取响应并将其保存在共享首选项中?

【问题讨论】:

  • 您可以在此处找到有关 json 解析器的教程:tutorialspoint.com/android/android_json_parser.htm 以及此处的共享首选项:tutorialspoint.com/android/android_shared_preferences.htm
  • @pooya 我知道 json 解析。但在这种情况下,如果您检查 url,则只有一个对象显示哪个是响应。我很困惑如何解析它。请解释一下。
  • 它仍然是一个单值的 JSON 对象你创建一个新的 JSONObject 并执行 jsonObject.getBoolean("success")
  • @Pooya 你能帮我写代码吗?我无法解析单个对象。直到今天我已经用相同的方法解析了多个对象。我面临单身的麻烦。请!!

标签: java android json android-asynctask sharedpreferences


【解决方案1】:

这是一个您可以使用的示例代码:

protected Void doInBackground(Void... unused) {

    //TODO: add code to read http request and store the json data in json variable
    JSONObject jsonObject = new JSONObject(json);
    boolean state = jsonObject.getBoolean("success");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Editor editor = prefs.edit();
    editor.putBoolean("state",state);
    editor.commit();
    return null;

}

【讨论】:

  • 在 JSONObject jsonObject = new JSONObject(json);它说无法解析符号 json。
  • 看看我在评论中写的 TODO 部分。你需要读取http数据。这部分在你身上。我刚刚实现了解析
【解决方案2】:

首先,我建议您需要将 JSON 数据作为字符串获取并进行解析。

    String json = "";
    URL url;
    HttpURLConnection connection = null;


    try {
        url =  new URL("http://a.nextput.com/apps/init/4/a/9fe2d2cbaa8332a4633be17b79208181-2y-10-ELVM4HwkaYaCVu6203Zjfus-G/o?aff_id=");
        connection = (HttpURLConnection) url.openConnection();
        InputStream inputStream = connection.getInputStream();
        InputStreamReader reader = new InputStreamReader(inputStream);
        int data = reader.read();

        while (data != -1) {

            char currentChar = (char) data;
            data = reader.read();
            json += currentChar;


        }

    }catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return json;
}

我在 doInBackground 中调用这个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多