通过json发送多条记录到php mysql

时间:2013-08-13 02:53:39

标签: java php android sql json

如何使用json一次发送多条记录?这段代码是我在网上找到的一个例子,但我需要一次发送100个对象或记录。数据来自数据库。

protected String doInBackground(String... args) {
        String name = inputName.getText().toString();
        String price = inputPrice.getText().toString();
        String description = inputDesc.getText().toString();

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("name", name));
        params.add(new BasicNameValuePair("price", price));
        params.add(new BasicNameValuePair("description", description));

        // getting JSON Object
        // Note that create product url accepts POST method
        JSONObject json = jsonParser.makeHttpRequest(url_create_product,
                "POST", params);

2 个答案:

答案 0 :(得分:0)

您可以将数据列表写入String,然后将其发送到php url。在php json_decode中读取数据列表;

public static class Entity{
        private String name;
        private String price;
        private String description;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getPrice() {
            return price;
        }

        public void setPrice(String price) {
            this.price = price;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }

    @Test
    public void send() throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        List<Entity> list = new ArrayList<Entity>(); // get the list of Entity;
        String json = mapper.writeValueAsString(list); // write list as json

        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://url.to.post");

        StringEntity entity = new StringEntity(json);
        post.setEntity(entity);

        HttpResponse response = client.execute(post);

        String result = EntityUtils.toString(response.getEntity());
        Object responseObject = mapper.readValue(result, Object.class);
    }

为了使用ObjectMapper,您需要在libs中使用jackson-core-asl和jackson-mapper-asl。

答案 1 :(得分:0)

您必须创建表示对象的JSONObject,并将其添加到Request:

如果你有这样的结构,例如:

{[{名称: “NAME1”,价格: “10”},{名称: “NAME2”,价格 “15”}]}

 JSONArray elements=new JSONArray();
  JSONObject aux=new JSONObject().put("name", "name1");
    aux.put("price", 10);
    array.put(aux);

    aux=new JSONObject().put("name1", "name2");
    aux.put("price", 20);
    array.put(aux);

List<NameValuePair> parameters= new ArrayList<NameValuePair>();
parameters.add(new BasicNameValuePair("json", elements.toString()));
HttpPost post = new HttpPost(url);
post.setEntity(new UrlEncodedFormEntity(pairs));
HttpClient cliente = createHttpClient();
return cliente.execute(post);

在服务器中,您可以捕获参数“json”