0

I have to post such json using MultipartEntity.

{
arrayName":[
  {
    // object one
  },
  {
    // object two
  }]
}

I don't get an idea how to make such structure once posting multipartEntity object, what i have tried so far is.

MultipartEntity entity = new MultipartEntity();
entity.addPart("key","value");
.....
.....
..... all keys 
httppost.setEntity(entity);

Is there any way so i can make MultipartEntity array or what?

NOTE: for separate posting one json object it work very fine. I just want to learn how to create JSONarry format, once posting with MultipartEntity.

Mohsin
  • 1,586
  • 1
  • 22
  • 44

2 Answers2

0

You have to convert your json array to string.

Use Gson Library for that. Gson

Now you just have to use like this. Whatever you model is so

ArrayList<CustomClass> objects = new ArrayList<>();
objects.add(object);
objects.add(object);

and then just use gson.

String stringToPost = new Gson().toJson(objects);

then add multipart this string as

Stringbody

Server side will deserialize String to Json Array.

Also you can add file as filebody in multipart.

shreyash mashru
  • 301
  • 2
  • 9
0

This is an example to upload image and JSONArray using MultipartEntity-- lib:org.apache.http.entity.mime

List students = getStudentList();

MultipartEntity studentList = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

for(int i=0; i<students.size();i++){

    try {
        studentList.addPart("studentList[][name]", new StringBody(String.valueOf(students.get(i).getName())));
        studentList.addPart("studentList[][addmission_no]", new StringBody(String.valueOf(students.get(i).getAddmissionNo)));
        studentList.addPart("studentList[][gender]", new StringBody(String.valueOf(students.get(i).getGender)));

        File photoImg = new File(students.get(i).getImagePath());
        studentList.addPart("studentList[][photo]",new FileBody(photoImg,"image/jpeg"));


    }catch(Exception e){
        e.getMessage();
    }
}

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(URL);

post.addHeader("X-Auth-Token", mUserToken);
post.setEntity(studentList);

org.apache.http.HttpResponse response = null;
try {
    response =  client.execute(post);
} catch (IOException e) {
    e.printStackTrace();
}
HttpEntity httpEntity = response.getEntity();
JSONObject myObject;
try {
    String result = EntityUtils.toString(httpEntity);
   // do your work

} catch (IOException e) {
    e.printStackTrace();
}
Imeshke
  • 811
  • 6
  • 13