【问题标题】:Value at 0 cannot be converted to JSON Object0 处的值无法转换为 JSON 对象
【发布时间】:2019-04-02 05:15:47
【问题描述】:

我正在从SharedPreference 读取字符串数据。我的字符串格式是

[{
    "name": "sdf",
    "phone": "2356235623",
    "no_people": "2"
}]

我想阅读此JSONArray 中的所有JSONobjects。所以我将此字符串转换为 JSON 数组为

String tempData = addqueuetemp.getString("tempdata", "");
JSONArray cacheTemp=new JSONArray(tempData);

现在我将这个 JSON 数组解析为

 JSONArray cacheTemp=new JSONArray(tempQueue);
        for(int i=0;i<cacheTempQueue.length();i++){
            JSONObject tempObject=cacheTemp.getJSONObject(i);
            CurrentStatusEntry tempEntry=new CurrentStatusEntry();
            tempEntry.setName(tempObject.getString("name");
            current.add(tempEntry);
            adapter = new QueueAdapter(current, getActivity().getApplicationContext());
            recyclerView.setAdapter(adapter);
        }  

但我收到错误

org.json.JSONException: Value {"name":"sdf","phone":"2356235623","no_people":"2"} at 0 of type java.lang.String cannot be converted to JSONObject

如何解决这个问题?

【问题讨论】:

  • 什么是cacheTempQueue
  • 对不起它的 cacheTemp only
  • 您的代码在循环中重复地将适配器设置为您的 recyclerview,您可以将该代码移到 for 循环之外

标签: android arrays sharedpreferences android-json


【解决方案1】:

试试这个

JSONObject obj1 = new JSONObject(result.toString());
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
JSONObject dataObj = new JSONObject();
dataObj.put("Data", jsonArray);
JSONArray Jarray = obj.getJSONArray("value");

【讨论】:

    【解决方案2】:

    使用这个

    JSONArray cacheTemp=new JSONArray(tempQueue);
        for(int i=0;i<cacheTemp.length();i++){
            JSONObject tempObject=cacheTemp.getJSONObject(i);
            CurrentStatusEntry tempEntry=new CurrentStatusEntry();
            tempEntry.setName(tempObject.getString("name");
            current.add(tempEntry);
            adapter = new QueueAdapter(current, getActivity().getApplicationContext());
            recyclerView.setAdapter(adapter);
        }  
    

    【讨论】:

      【解决方案3】:

      在 for 循环中使用 cacheTemp JSONArray 代替 cacheTempQueue 并将您的 setAdateper 代码放到循环外。

      JSONArray cacheTemp=new JSONArray(tempQueue);
      for(int i=0;i<cacheTemp.length();i++){
              JSONObject tempObject=cacheTemp.getJSONObject(i);
              CurrentStatusEntry tempEntry=new CurrentStatusEntry();
              tempEntry.setName(tempObject.getString("name");
              current.add(tempEntry);
      }  
      
      adapter = new QueueAdapter(current, getActivity().getApplicationContext());
      recyclerView.setAdapter(adapter);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-13
        • 1970-01-01
        • 2019-12-23
        • 1970-01-01
        相关资源
        最近更新 更多