从空 sharedpreference 中检索 json 数组时,java.lang.String 无法转换为 JSONObject 异常出现

Posted

技术标签:

【中文标题】从空 sharedpreference 中检索 json 数组时,java.lang.String 无法转换为 JSONObject 异常出现【英文标题】:When retrieving json array from empty sharedpreference, java.lang.String cannot be converted to JSONObject exception comes 【发布时间】:2021-10-22 11:32:06 【问题描述】:

W/System.err: org.json.JSONException: value Responsemodel$Banner@b494bac at 0 of type java.lang.String 无法转换为 JSONObject

输出:

[Responsemodel$Banner@e5af3c3, Responsemodel$Banner@ed16440, Responsemodel$Banner@5335f79, Responsemodel$Banner@e8cb4be, Responsemodel$Banner@9ef091f]

从 SharedPreferences 获取

String getbanner = preferences.getString(Constants.banner_list, null);
        Log.i("banner_str", getbanner);
        if (getbanner != null) 
            JSONArray jsonArray2 = new JSONArray(getbanner);
            Log.i("Sharedpref1", jsonArray2.toString());
            if (banner_list != null) 
                banner_list.clear();
                Log.i("Sharedpref2", jsonArray2.toString());
                for (int x = 0; x < jsonArray2.length(); x++) 
                    String object = jsonArray2.getJSONObject(x).getString("imgUrl");
                    Log.i("bid", object);
                    HashMap<String, String> map = new HashMap<>();
                    map.put("imgUrl", object);
                    banner_list.add(map);
                
            
        

     catch (NullPointerException | JSONException e1) 
        e1.printStackTrace();
    
    Banner_adapter adapter1 = new Banner_adapter(banner_list);
    snapHelper.attachToRecyclerView(recyclerView);
    recyclerView.setAdapter(adapter1);
    adapter1.notifyDataSetChanged();

保存在 SharedPreferences 中

getbalres_dto model = response.body(); SharedPreferences.Editor editor = preferences.edit();
                editor.putString(Constants.currentBalance, model.getMOBILEAPPLICATION().getCurrentBalance())
                        .putString(Constants.outletName, model.getMOBILEAPPLICATION().getOutletName())
                        .putString(Constants.name, model.getMOBILEAPPLICATION().getName())
                        .putString(Constants.news, model.getMOBILEAPPLICATION().getNews())
                        .putString(Constants.banner_list, model.getMOBILEAPPLICATION().getBanner().toString())
                        .putString(Constants.instaurl, model.getMOBILEAPPLICATION().getInstagramUrl())
                        .putString(Constants.fburl, model.getMOBILEAPPLICATION().getFacebookUrl())
                        .putString(Constants.youtubeurl, model.getMOBILEAPPLICATION().getYoutubeUrl())
                        .putString(Constants.twitterurl, model.getMOBILEAPPLICATION().getTwitterUrl())
                        .putString(Constants.aepsBalance, model.getMOBILEAPPLICATION().getAepsBalance())
                        .putString(Constants.cartItem, model.getMOBILEAPPLICATION().getCartItem())
                        .commit();

Java PoJO 类

public class getbalres_dto 

@SerializedName("MOBILE_APPLICATION")
@Expose
private MOBILEAPPLICATION mOBILEAPPLICATION;

public MOBILEAPPLICATION getMOBILEAPPLICATION() 
    return mOBILEAPPLICATION;


public void setMOBILEAPPLICATION(MOBILEAPPLICATION mOBILEAPPLICATION) 
    this.mOBILEAPPLICATION = mOBILEAPPLICATION;


public class MOBILEAPPLICATION 

    @SerializedName("response")
    @Expose
    private String response;
    @SerializedName("Message")
    @Expose
    private String message;
    @SerializedName("news")
    @Expose
    private String news;
    @SerializedName("banner")
    @Expose
    private JsonArray banner;
    @SerializedName("name")
    @Expose
    private String name;
    @SerializedName("outletName")
    @Expose
    private String outletName;
    @SerializedName("currentBalance")
    @Expose
    private String currentBalance;
    @SerializedName("aepsBalance")
    @Expose
    private String aepsBalance;

    @SerializedName("activationAmount")
    @Expose
    private String activationAmount;

    @SerializedName("transactionAmount")
    @Expose
    private String transactionAmount;

    @SerializedName("totalAmount")
    @Expose
    private String totalAmount;

    @SerializedName("isPaid")
    @Expose
    private String isPaid;

    @SerializedName("rentalType")
    @Expose
    private String rentalType;
    @SerializedName("instagramUrl")
    @Expose
    private String instagramUrl;
    @SerializedName("twitterUrl")
    @Expose
    private String twitterUrl;
    @SerializedName("facebookUrl")
    @Expose
    private String facebookUrl;
    @SerializedName("youtubeUrl")
    @Expose
    private String youtubeUrl;

    @SerializedName("cartItem")
    @Expose
    private String cartItem;

    public String getAepsBalance() 
        return aepsBalance;
    

    public void setAepsBalance(String aepsBalance) 
        this.aepsBalance = aepsBalance;
    

    public String getInstagramUrl() 
        return instagramUrl;
    

    public void setInstagramUrl(String instagramUrl) 
        this.instagramUrl = instagramUrl;
    

    public String getTwitterUrl() 
        return twitterUrl;
    

    public void setTwitterUrl(String twitterUrl) 
        this.twitterUrl = twitterUrl;
    

    public String getFacebookUrl() 
        return facebookUrl;
    

    public void setFacebookUrl(String facebookUrl) 
        this.facebookUrl = facebookUrl;
    

    public String getYoutubeUrl() 
        return youtubeUrl;
    

    public void setYoutubeUrl(String youtubeUrl) 
        this.youtubeUrl = youtubeUrl;
    

    public String getRentalType() 
        return rentalType;
    

    public void setRentalType(String rentalType) 
        this.rentalType = rentalType;
    

    public String getIsPaid() 
        return isPaid;
    

    public void setIsPaid(String isPaid) 
        this.isPaid = isPaid;
    

    public String getTotalAmount() 
        return totalAmount;
    

    public void setTotalAmount(String totalAmount) 
        this.totalAmount = totalAmount;
    

    public String getTransactionAmount() 
        return transactionAmount;
    

    public void setTransactionAmount(String transactionAmount) 
        this.transactionAmount = transactionAmount;
    

    public String getActivationAmount() 
        return activationAmount;
    

    public void setActivationAmount(String activationAmount) 
        this.activationAmount = activationAmount;
    

    public String getResponse() 
        return response;
    

    public void setResponse(String response) 
        this.response = response;
    

    public String getMessage() 
        return message;
    

    public void setMessage(String message) 
        this.message = message;
    

    public String getNews() 
        return news;
    

    public void setNews(String news) 
        this.news = news;
    

    public JsonArray getBanner() 
        return banner;
    

    public void setBanner(JsonArray banner) 
        this.banner = banner;
    

    public String getName() 
        return name;
    

    public void setName(String name) 
        this.name = name;
    

    public String getOutletName() 
        return outletName;
    

    public void setOutletName(String outletName) 
        this.outletName = outletName;
    

    public String getCartItem() 
        return cartItem;
    

    public void setCartItem(String cartItem) 
        this.cartItem = cartItem;
    

    public String getCurrentBalance() 
        return currentBalance;
    

    public void setCurrentBalance(String currentBalance) 
        this.currentBalance = currentBalance;
    

【问题讨论】:

【参考方案1】:

从 SharedPreference 获取

 String getbanner = preferences.getString(Constants.banner_list, null);
    Gson gson = new Gson();
    Log.i("bannerdata__", getbanner);
    try 
        if (getbanner.isEmpty() || getbanner==null || getbanner.equalsIgnoreCase(null)) 
            Log.i("bannerdata__", "empty......");
         else 
            Type type = new TypeToken<List<String>>() 

            .getType();
            List<String> data = gson.fromJson(getbanner, type);

            for (String imgstr : data) 
                Log.i("bannerdata_2", imgstr);

                HashMap<String, String> map = new HashMap<>();
                map.put("imgUrl", imgstr);
                banner_list.add(map);
            

            Banner_adapter adapter1 = new Banner_adapter(banner_list);
            snapHelper.attachToRecyclerView(recyclerView);
            recyclerView.setAdapter(adapter1);
            adapter1.notifyDataSetChanged();

        

     catch (Exception e) 
        e.printStackTrace();
    

在 SharedPreference 中添加数据

   final ArrayList<String> arrPackage = new ArrayList<>();
                try 
                    JSONArray jsonArray2 = new JSONArray(getbalmodel.getMOBILEAPPLICATION().getBanner().toString());

                    if (banner_list != null) 
                        banner_list.clear();
                    

                    for (int x = 0; x < jsonArray2.length(); x++) 
                        String bid = jsonArray2.getJSONObject(x).getString("imgUrl");

                        arrPackage.add(bid);

                        Gson gson = new Gson();
                        String json = gson.toJson(arrPackage);
                        editor.putString(Constants.banner_list, json);

                        Log.i("imageurl", bid);


                        HashMap<String, String> map = new HashMap<>();
                        map.put("imgUrl", bid);
                        banner_list.add(map);

                    

                    editor.commit();

                 catch (JSONException | NullPointerException e1) 
                    e1.printStackTrace();
                

【讨论】:

以上是关于从空 sharedpreference 中检索 json 数组时,java.lang.String 无法转换为 JSONObject 异常出现的主要内容,如果未能解决你的问题,请参考以下文章

从SharedPreferences保存并检索Intent

尝试从 sharedPreferences 检索地图时出现颤振错误

我可以使用一个按钮将数据保存在 sharedPreferences 中,然后使用另一个按钮来检索它吗?

无法从SharedPreferences检索数据?

尝试使用 SharedPreferences 存储和检索应用程序数据,但它没有返回所需的数据

Android数据存储SharedPreferences