【问题标题】:How to add jsonobject in to jsonarray which i want如何将 jsonobject 添加到我想要的 jsonarray
【发布时间】:2017-03-29 16:40:34
【问题描述】:

我只能在这张图片的左侧添加jsonobj和json obj

但是如果我想添加像右手边这样的数据,我应该在我的代码中添加什么代码 (我想知道如何指定要添加的 json 数组的标题) (来自 ThinkTwiceCodeOnce 的信用代码) 我的代码是...

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {

    ProgressDialog progressDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        progressDialog = new ProgressDialog(MainActivity.this);
        progressDialog.setMessage("Inserting data...");
        progressDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {

        try {
            return postData(params[0]);
        } catch (IOException ex) {
            return "Network error !";
        } catch (JSONException ex) {
            return "Data Invalid !";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        mResult.setText(result);

        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }

    private String postData(String urlPath) throws IOException, JSONException {

        StringBuilder result = new StringBuilder();
        BufferedWriter bufferedWriter = null;
        BufferedReader bufferedReader = null;

        try {
            //Create data to send to server
            JSONObject dataToSend = new JSONObject();
            dataToSend.put("name", "puggy");
            dataToSend.put("like", "dog");
            dataToSend.put("eat", "meat");
            dataToSend.put("fav", "red balloon");

            //Initialize and config request, then connect to server.
            URL url = new URL(urlPath);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /* milliseconds */);
            urlConnection.setConnectTimeout(10000 /* milliseconds */);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);  //enable output (body data)
            urlConnection.setRequestProperty("Content-Type", "application/json");// set header
            urlConnection.connect();

            //Write data into server
            OutputStream outputStream = urlConnection.getOutputStream(); 
            bufferedWriter = new BufferedWriter(new              OutputStreamWriter(outputStream));
            bufferedWriter.write(dataToSend.toString());
            bufferedWriter.flush();
            //Read data response from server
            InputStream inputStream = urlConnection.getInputStream();
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line).append("\n");
            }
        } finally {
            if (bufferedReader != null) {
                bufferedReader.close();
            }
            if (bufferedWriter != null) {
                bufferedWriter.close();
            }
        }

        return result.toString();
    }
}

【问题讨论】:

    标签: java android arrays json


    【解决方案1】:

    使用dataToSend.put("profile", JSONArrayProfile) 将配置文件JSONArray 添加到JSONObject

    这是工作代码。试试这个:

    try {
            JSONObject dataToSend = new JSONObject();
    
            // Profile
            JSONArray jsonArrayProfile = new JSONArray();
    
            // Post 1
            JSONObject jsonObjectPost1 = new JSONObject();
            jsonObjectPost1.put("fbname", "Think Twice Code Once");
            jsonObjectPost1.put("content", "felling full");
            jsonObjectPost1.put("likes", 1);
            jsonObjectPost1.put("comments", 3);
    
            // Post 2
            JSONObject jsonObjectPost2 = new JSONObject();
            jsonObjectPost2.put("fbname", "Think Twice Code Once");
            jsonObjectPost2.put("content", "felling full");
            jsonObjectPost2.put("likes", 1);
            jsonObjectPost2.put("comments", 3);
    
            // Add post1, post2 jsonObject to profile jsonArray
            jsonArrayProfile.put(jsonObjectPost1);
            jsonArrayProfile.put(jsonObjectPost2);
    
            // Add profile jsonArray to jsonObject
            dataToSend.put("profile", jsonArrayProfile);
    
            Log.d("SUCCESS", "JSON: " + dataToSend.toString());
    
        } catch (final JSONException e) {
            Log.e("FAILED", "Json build error: " + e.getMessage());
        }
    

    输出:

            {
                "profile":[
                    {
                        "fbname":"Think Twice Code Once",
                        "content":"felling full",
                        "likes":1,
                        "comments":3
                    },
                    {
                        "fbname":"Think Twice Code Once",
                        "content":"felling full",
                        "likes":1,
                        "comments":3
                    }
                ]
            }
    

    【讨论】:

    • @YY.theFenix 这个答案应该被接受。
    【解决方案2】:

    你可以使用下面的代码来试试。

    JSONArray ja = new JSONArray();
    ja.put(dataToSend);
    

    【讨论】:

      【解决方案3】:

      你必须以这种方式创建 JSON 对象

      JSONObject dataToSend = new JSONObject();
      JSONArray arrayData = new JSONArray();
      dataToSend.put("profile",arrayData);
      

      如果您想将 JSON 对象添加到您的 JSONArray 中,请使用此

      arrayData.put(JSONObject1);
      arrayData.put(JSONObject2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-21
        • 2016-12-03
        • 1970-01-01
        • 2021-06-21
        • 1970-01-01
        • 2021-05-09
        • 2018-11-14
        • 1970-01-01
        相关资源
        最近更新 更多