1

I have some data in the database I want to send the data in a json

       {"name":"Ram","age":20},
       {"name":"michael","age":25},
       {"name":"Suma","age":28}

I want to send all the records to a web api at a time. right now I am sending one by one how can I post this json.How to assign json object to a json array dynamically.?

     JSONObject obj = new JSONObject();
   try {

    obj.put("Name","Ram");
    obj.put("age",20);

    HttpContext httpContext = new BasicHttpContext();
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 2000);
    HttpConnectionParams.setSoTimeout(httpParameters, 2000);
    HttpClient httpClient = new DefaultHttpClient(httpParameters);
    HttpPost httpPost = new HttpPost("myurl");
    try {
        StringEntity se = new StringEntity(obj.toString());
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        HttpResponse response = httpClient.execute(httpPost, httpContext); //execute your        HttpEntity entity = response.getEntity();
        String jsonString = EntityUtils.toString(entity); //if response in JSON format
        System.out.println("Respone: "+jsonString); 
5
  • create json array with multiple JSONobjects and pass it server via httppost Commented Jun 17, 2014 at 10:35
  • Can you answer to my question It would be greate If you can Commented Jun 17, 2014 at 10:42
  • be more specific what you want.. Commented Jun 17, 2014 at 10:45
  • I want to send all the data at one go. Commented Jun 17, 2014 at 10:48
  • does that code works? Commented Jun 17, 2014 at 11:06

1 Answer 1

1

Try this to create JSON ARRAY..

JSONArray myArray = new JSONArray();

JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);
JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);
JSONObject j = new JSONObject();
    j.put("key",value);
    j.put("key",value);
    myarray.put(j);

JSONObject finalObject = new JSONObject();
finalObject.put("Name", myarray);

and then pass finalObject it as string

Sign up to request clarification or add additional context in comments.

1 Comment

not working for me...my final call encode array as string...i dnt knw why

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.