Java 如何将jsonobject添加到我想要的jsonarray中

Java 如何将jsonobject添加到我想要的jsonarray中,java,android,arrays,json,Java,Android,Arrays,Json,我只能在图的左侧添加jsonobj和json obj 但若我想添加数据,比如右侧,我应该向代码中添加什么代码 (我想知道如何指定要添加的json数组的头) (来自ThinkTwiceCodeOnce的信用代码) 我的代码是 protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);

我只能在图的左侧添加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();
    }
}
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar Toolbar=(Toolbar)findViewById(R.id.Toolbar);
设置支持操作栏(工具栏);
新建PostDataTask()。执行(“http:///api/status");
}
类PostDataTask扩展了AsyncTask{
进行对话进行对话;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
progressDialog=新建progressDialog(MainActivity.this);
progressDialog.setMessage(“插入数据…”);
progressDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
试一试{
返回postData(参数[0]);
}捕获(IOEX异常){
返回“网络错误!”;
}捕获(JSONException ex){
返回“数据无效!”;
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
mResult.setText(结果);
如果(progressDialog!=null){
progressDialog.disclose();
}
}
私有字符串postData(字符串urlPath)抛出IOException、jsoneexception{
StringBuilder结果=新建StringBuilder();
BufferedWriter BufferedWriter=null;
BufferedReader BufferedReader=null;
试一试{
//创建要发送到服务器的数据
JSONObject dataToSend=新的JSONObject();
dataToSend.put(“name”,“puggy”);
dataToSend.put(“like”、“dog”);
数据发送。放置(“吃”、“肉”);
dataToSend.put(“fav”、“红气球”);
//初始化并配置请求,然后连接到服务器。
URL=新URL(URL路径);
HttpURLConnection urlConnection=(HttpURLConnection)url.openConnection();
setReadTimeout(10000/*毫秒*/);
setConnectTimeout(10000/*毫秒*/);
urlConnection.setRequestMethod(“POST”);
urlConnection.setDoOutput(true);//启用输出(正文数据)
urlConnection.setRequestProperty(“内容类型”,“应用程序/json”);//集头
urlConnection.connect();
//将数据写入服务器
OutputStream OutputStream=urlConnection.getOutputStream();
bufferedWriter=新的bufferedWriter(新的OutputStreamWriter(outputStream));
bufferedWriter.write(dataToSend.toString());
bufferedWriter.flush();
//从服务器读取数据响应
InputStream InputStream=urlConnection.getInputStream();
bufferedReader=新的bufferedReader(新的InputStreamReader(inputStream));
弦线;
而((line=bufferedReader.readLine())!=null){
结果.append(行).append(“\n”);
}
}最后{
if(bufferedReader!=null){
bufferedReader.close();
}
if(bufferedWriter!=null){
bufferedWriter.close();
}
}
返回result.toString();
}
}

您可以使用以下代码进行尝试

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

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

JSONObject dataToSend = new JSONObject();
JSONArray arrayData = new JSONArray();
dataToSend.put("profile",arrayData);
如果您想将JSON对象添加到JSONArray中,请使用以下命令

arrayData.put(JSONObject1);
arrayData.put(JSONObject2);
使用
dataToSend.put(“profile”,JSONArrayProfile)
将profile
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
                }
            ]
        }
输出:

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
                }
            ]
        }

@这个答案应该被接受。