Skip to content Skip to sidebar Skip to footer

Send Multiple Records Via Json To Php Mysql

How do I send more than one record at a time using json? This code is a sample I found online but I need to send say 100 objects or records at a time. The data comes from a datab

Solution 1:

You must create the JSONObject that represent the objects, and add it to the Request:

If you have this structure for example:

{[{name:"name1",price:"10"},{name:"name2",price:"15"}]}

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

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

List<NameValuePair> parameters= newArrayList<NameValuePair>();
parameters.add(newBasicNameValuePair("json", elements.toString()));
HttpPost post = newHttpPost(url);
post.setEntity(newUrlEncodedFormEntity(pairs));
HttpClient cliente = createHttpClient();
return cliente.execute(post);

And in the server you catch the parameter "json"

Solution 2:

You can write the list of data to String, then send it to php url. In php json_decode to read the list of data;

publicstaticclassEntity{
        privateString name;
        privateString price;
        privateString description;

        publicStringgetName() {
            return name;
        }

        publicvoidsetName(String name) {
            this.name = name;
        }

        publicStringgetPrice() {
            return price;
        }

        publicvoidsetPrice(String price) {
            this.price = price;
        }

        publicStringgetDescription() {
            return description;
        }

        publicvoidsetDescription(String description) {
            this.description = description;
        }
    }

    @Testpublicvoidsend() throws Exception{
        ObjectMapper mapper = newObjectMapper();
        List<Entity> list = newArrayList<Entity>(); // get the list of Entity;String json = mapper.writeValueAsString(list); // write list as jsonHttpClient client = newDefaultHttpClient();
        HttpPost post = newHttpPost("http://url.to.post");

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

        HttpResponse response = client.execute(post);

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

In order to use ObjectMapper you will need jackson-core-asl and jackson-mapper-asl in your libs.

Post a Comment for "Send Multiple Records Via Json To Php Mysql"