首页 > 解决方案 > 如何在 json url 中添加对象?

问题描述

我正在做一个涉及 json 的程序,我想问如果添加了一个新对象,我该如何更新 json URL,例如我在 URL 中有一个名为苹果、香蕉和橙子的食物对象。如何在 URL 中添加草莓?这是我的 JSON URL MyJSON如何在 foodname 中添加一个对象,例如鸡肉?有人帮忙吗?这是我的代码,到目前为止我只能访问它但不能更新它。

class JSONParser extends AsyncTask<String, Void, Boolean> {

    private ProgressDialog dialog;
    private String un;
    private String ea;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        //displays the loading window for when connecting to the server
        dialog = new ProgressDialog(Food.this);
        dialog.setMessage("Loading, please wait.");
        dialog.setTitle("Connecting to Server");
        dialog.show();
        dialog.setCancelable(false);
    }
    //this is the doInBackground method, this is where we retrieve and parse data from the aforementioned JSON URL
    @Override
    protected Boolean doInBackground(String... urls) {
        try {
            //connects to the JSON URL found inside the execute method here => new JSONParser().execute("https://api.myjson.com/bins/809o6");
            HttpGet httppost = new HttpGet(urls[0]);
            HttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httppost);

            //if status = 200 it means that it successfully established a connection with the JSON URL
            int status = response.getStatusLine().getStatusCode();
            if (status == 200) {

                HttpEntity entity = response.getEntity();

                //gets all the JSON data (JSON objects and arrays) found inside the JSON URL
                String data = EntityUtils.toString(entity);

                JSONObject root = new JSONObject(data);
                JSONObject rootObj = root.getJSONObject("justincorilla@yahoo.com");
                JSONArray array = rootObj.getJSONArray("foods");
                for(int i = 0; i<array.length();i++){

                    JSONObject obj = array.getJSONObject(i);
                    FoodInformation food = new FoodInformation();
                    food.setFoodName(obj.getString("foodName"));
                    food.setExpiryDate(obj.getString("expiryDate"));

                    //adds a all the parsed JSON data to the Array List "foodList"
                    foodList.add(food);
                }
                return true;
            }

        }
        catch (ParseException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch(Exception e){
            e.printStackTrace();
        }
        return false;
    }

标签: androidjson

解决方案


推荐阅读