如何使用json将json数组发送到服务器?

时间:2015-11-06 16:07:53

标签: android

我是android的初学者,我在我的sqlite数据库上有这些数据:
enter image description here


现在我想发送该表的一行:
我创建了这个类:

public class TourMyCountry {
        String NAME;
        String FAMILY;
        String ID;


    }


并在android按钮单击事件中编写此代码:

new HttpAsyncTask().execute("http://myHOST.ir/getLIST.aspx");


并写下这段代码:

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            TourMyCountry country = new TourMyCountry();

            country.ID =//READ DATA FROM SQLITE
            country.NAME=//READ DATA FROM SQLITE
            country.FAMILY=//READ DATA FROM SQLITE

            return POST(urls[0], country);
        }
@Override
        protected void onPostExecute(String result) {

        }

    }
//-----------------------
//**************************************POST LEVEL
    public static String POST(String url, TourMyCountry myCountry) {
        InputStream inputStream = null;
        String result = "";
        try {
            // 1. create HttpClient
            HttpClient httpclient = new DefaultHttpClient();
            // 2. make POST request to the given URL
            HttpPost httpPost = new HttpPost(url);
            String json = "";
            // 3. build jsonObject
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("id", myCountry.id);
            jsonObject.accumulate("name", myCountry.NAME);
            jsonObject.accumulate("family", myCountry.FAMILY);

            json = jsonObject.toString();
            StringEntity se = new StringEntity(json);
            json = jsonObject.toString();
            httpPost.setEntity(new StringEntity(json.toString(),"UTF-8"));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);
           inputStream = httpResponse.getEntity().getContent();
            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";

        }//end of try
        catch (Exception e) {
            Log.d("InputStream", e.getLocalizedMessage());
        }//end of catch

        // 11. return result
        return result;
    }//end of POST method
//-----------------------------
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;
    }


代码只发送一行,并且工作得很好,但我想发送上表的所有数据,我该如何解决?我可以创建json或其他方式的数组吗?感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在解析它并将其发送到服务器之前,您可以使用JSONArray在其中存储 JSONObject

代码:

preg_replace