2016-02-04 54 views
0

我必須擊中json服務,並且如果響應成真,則必須將用戶值保存在共享首選項中供將來使用。我怎樣才能做到這一點?如何在共享首選項中保存json響應的值?

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

變量將由SDK用戶通過。在上面的url中,我的變量是: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(); 
    } 

} 

請告訴我如何解析它以獲取響應並將其保存在共享首選項中?

+0

你可以在這裏找到關於json解析器的教程:http://www.tutorialspoint.com/android/android_json_parser.htm&for sharedpreferences here:http://www.tutorialspoint.com/android/android_shared_preferences.htm – Pooya

+0

@ pooya我知道json解析。但在這種情況下,如果您檢查網址,則只有一個對象顯示哪個是響應。我很困惑如何解析它。請解釋。 –

+0

它仍然是一個具有單個值的JSON對象,您可以創建一個新的JSONObject並執行jsonObject.getBoolean(「success」) – Pooya

回答

0

這裏是一個示例代碼,你可以使用:

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; 

} 
+0

在行JSONObject jsonObject = new JSONObject(json);它說不能解析符號json。 –

+0

看看我在評論中寫的TODO部分。你需要閱讀http數據。這部分在你身上。我剛剛實施瞭解析 – Pooya

0

首先,我建議你需要得到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裏面調用了這個方法。