无法将数据解析为recyclerview

时间:2017-03-02 06:55:30

标签: java android json

我正在尝试将json放入recyclerview,但它让我“无法解析dara”错误!

这是我的json回复:

  

{ “行动”: “真”, “错误”: “”, “数据”:[{ “_ ID”: “58ad8d8ca49d0e11e21c4504”, “STORE_NAME”: “firstStore”, “store_view”:0, “store_textposition”日期null}]}

还有我收到错误“Shops_parser.java”:

    public class Shops_Parser extends AsyncTask<Void,Void,Boolean> {
    Context c;
    String jsonData;
    RecyclerView rv;
    ProgressDialog pd;
    ArrayList<String> shops = new ArrayList<>();

    public Shops_Parser(Context c, String jsonData, RecyclerView rv) {
        this.c = c;
        this.jsonData = jsonData;
        this.rv = rv;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd=new ProgressDialog(c);
        pd.setMessage("PARSING JSON");
        pd.show();
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        return parse();
    }

    @Override
    protected void onPostExecute(Boolean isParsed) {
        super.onPostExecute(isParsed);
        pd.dismiss();
        if(isParsed)
        {
            ShopsAdapter adapter = new ShopsAdapter(c,shops);
            rv.setAdapter(adapter);
        }
        else
        {
            Toast.makeText(c,"Unable to Parse data",Toast.LENGTH_SHORT).show();
        }
    }

    private boolean parse()
    {
        try
        {
            JSONArray ja = new JSONArray(jsonData);
            JSONObject jo;
            shops.clear();
            for(int i=0;i<ja.length();i++)
            {
                jo=ja.getJSONObject(i);
                String store_name = jo.getString("store_name");
                shops.add(store_name);
            }
            return true;
        }
        catch (JSONException e)
        {
            e.printStackTrace();
            return false;
        }
    }
}

它出了什么问题?

5 个答案:

答案 0 :(得分:2)

你的根元素是一个json对象。首先解析对象然后获取json数组

  try
    {
        JSONObject obj = new JSONObject(jsonData);
        JSONArray ja = obj.getJsonArray("data");
        JSONObject jo;
        shops.clear();
        for(int i=0;i<ja.length();i++)
        //................

答案 1 :(得分:1)

首先阅读 JSON

  

{ “行动”: “真”, “错误”: “”, “数据”:[{ “_ ID”: “58ad8d8ca49d0e11e21c4504”, “STORE_NAME”: “firstStore”, “store_view”:0, “store_textposition”日期null}]}

以这种方式纠正您的代码

JSONObject obj = new JSONObject(jsonData); // Problem here
JSONArray jsonArray= obj.getJsonArray("data");
for(int i=0;i<jsonArray.length();i++)
        {
           // your code
        }

希望这会对你有所帮助。

答案 2 :(得分:0)

您的解析功能应如下所示。

private boolean parse()
    {
        try
        {
            JSONObject ja = new JSONObject(jsonData);
            JSONArray dataArray = ja.getJSONArray("data");
            shops.clear();
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject jo  = dataArray.getJSONObject(i);
                String store_name = jo.getString("store_name");
                shops.add(store_name);
            }
            return true;
        }
        catch (JSONException e)
        {
            e.printStackTrace();
            return false;
        }
    }

答案 3 :(得分:0)

您可以将现有的解析逻辑替换为GSON。这将加速&amp;提高生产力。

开始使用,

创建2个POJO类,

<强> Data.class

public class Data {

    @SerializedName("_id")
    @Expose
    private String id;
    @SerializedName("store_name")
    @Expose
    private String storeName;
    @SerializedName("store_view")
    @Expose
    private Integer storeView;
    @SerializedName("store_textposition")
    @Expose
    private Object storeTextposition;

    public String getId() {
    return id;
    }

    public void setId(String id) {
    this.id = id;
    }

    public String getStoreName() {
    return storeName;
    }

    public void setStoreName(String storeName) {
    this.storeName = storeName;
    }

    public Integer getStoreView() {
    return storeView;
    }

    public void setStoreView(Integer storeView) {
    this.storeView = storeView;
    }

    public Object getStoreTextposition() {
    return storeTextposition;
    }

    public void setStoreTextposition(Object storeTextposition) {
    this.storeTextposition = storeTextposition;
    }

    }

<强> Store.class

public class Store {

@SerializedName("action")
@Expose
private String action;
@SerializedName("error")
@Expose
private String error;
@SerializedName("data")
@Expose
private List<Data> data = null;

public String getAction() {
return action;
}

public void setAction(String action) {
this.action = action;
}

public String getError() {
return error;
}

public void setError(String error) {
this.error = error;
}

public List<Data> getData() {
return data;
}

public void setData(List<Data> data) {
this.data = data;
}

}

现在在main活动中,声明一个私有变量并初始化它。

private List<Store> store;

在AsyncTask中添加以下代码,

@Override
        protected String doInBackground(Void... params) {
            try {
                //Create an HTTP client
                HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost(SERVER_URL);

                //Perform the request and check the status code
                HttpResponse response = client.execute(post);
                StatusLine statusLine = response.getStatusLine();
                if(statusLine.getStatusCode() == 200) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = entity.getContent();

                    try {
                        Reader reader = new InputStreamReader(content);
                        GsonBuilder gsonBuilder = new GsonBuilder();
                 gsonBuilder.setDateFormat("M/d/yy hh:mm a");
                        Gson gson = gsonBuilder.create();
                        List<Store> store = new ArrayList<Store>();
                        store = Arrays.asList(gson.fromJson(reader, Store[].class));
                        content.close();

                        handlePostsList(posts);
                    } catch (Exception ex) {
                        Log.e(TAG, "Failed to parse JSON due to: " + ex);
                    }
                }
            } catch(Exception ex) {
                Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
            }
            return null;
        } 

最后,您将获得一个包含GSON解析数据的商店对象列表。

要获取商店对象的任何属性e..g store_name ,只需调用

即可
String store_name = store.get(position).getStoreName();

答案 4 :(得分:0)

使用下面的代码来解析你的json响应:

 private void  parse(String jsonData)
    {
        try
        {
            JSONObject jsonObject = new JSONObject(jsonData);
            String action = jsonObject.optString("action");
            String error = jsonObject.optString("error");
            JSONArray dataArray = jsonObject.getJSONArray("data");
            shops.clear();
            for(int i=0;i<dataArray.length();i++)
            {
                JSONObject jsonObject1 = dataArray.getJSONObject(i);
                String _id = jsonObject1.optString("_id");
                String store_name = jsonObject1.optString("store_name");
                String store_view = jsonObject1.optString("store_view");
                String store_textposition = jsonObject1.optString("store_textposition");
                shops.add(store_name);
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
    }