2016-06-17 11 views
0

IDと最小数量を共有優先度に格納された配列のJSONオブジェクトに変換する必要があります。 VolleyのJSONオブジェクトから文字列IDと最小数量を取得できます。下記のJSONのように、オブジェクトの共有優先配列に格納する必要があります。配列のオブジェクトをAndroidの共有設定に保存する方法

JSON:

{ 
    [ 
    "producutid" : 1 
    "minqty"  : 5 
    ] 
    , 
    [ 
    "producutid" : 2 
    "minqty"  : 5 
    ] 
, 
[ 
    "producutid" : 3 
    "minqty"  : 5 
    ] 
, 
[ 
    "producutid" : 4 
    "minqty"  : 5 
    ]  

}

MyWorkingCode(私は共有好みにこのように格納したい):私は

String channel = shared.getString(Constants.cartid, "{'[]','[]'}"); 
JSONArray items = null; 
String wishitem; 
JSONObject jo = null; 
if (TextUtils.isEmpty(channel)) { 
    jo = new JSONObject(); 

    try { 
     jo.getJSONArray(String.valueOf(0)).put(String.valueOf(productpathid)); 
     jo.getJSONArray(String.valueOf(1)).put(String.valueOf(minqty)); 
    } catch (JSONException e) { 
     e.printStackTrace(); 
    } 
    wishitem = String.valueOf(items); 
    editor.putString(Constants.cartid, wishitem); 
    editor.apply(); 

} else { 

    try { 

     Boolean found = false; 
     jo = new JSONObject(String.valueOf(channel)); 
     items = jo.getJSONArray(String.valueOf(0)); 
     for (int x = 0; x < items.length(); x++) { 
      if (productpathid.equalsIgnoreCase(items.getString(x))) { 
       found = true; 
      } 
     } 
     if (!found) { 
      try { 
       jo.getJSONArray(String.valueOf(0)).put(String.valueOf(productpathid)); 
       jo.getJSONArray(String.valueOf(1)).put(String.valueOf(minqty)); 
      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
      wishitem = String.valueOf(items); 
      editor.putString(Constants.cartid, wishitem); 
      editor.apply(); 
     } 
     editor.apply(); 

    } catch (JSONException e) { 
     e.printStackTrace(); 
    }} 

私が得たエラー

org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject 

いくつかの間違いは、このコードの解決策を教えてください。 ありがとうございました。

答えて

0
ArrayListの

として、それを取り戻すに優先して、オブジェクトのストアArrayListに

Gson gson = new Gson(); 
... 
ArrayList<CategoriesEntity> alSelectedCategories = new ArrayList<CategoriesEntity>(); 
... 
String selectedCategory = gson.toJson(alSelectedCategories); 
ApplicationPreferences.setValue("SelectedCategory", selectedCategory, activity); 

をこの

Gson依存

compile 'com.google.code.gson:gson:2.6.1' 

を簡素化する

使用GoogleのGsonライブラリー

UserSelectedCategory = ApplicationPreferences.getValue("SelectedCategory", activity); if (UserSelectedCategory != null) { Type type = new TypeToken<ArrayList<CategoriesEntity>>() {}.getType(); alSelectedCategories = gson.fromJson(UserSelectedCategory, type); } 
+0

はモデルです。私は共有の設定を保存するためにモデルを使用しません – hem

+0

あなたはどんなデータ型 –

関連する問題