2

I have an ArrayList of Integers that I need to put into my MultipartBody.Builder. I have tried using different methods of .addFormDataPart, even tried to convert the arraylist to a JSONObject and then the JSONObject to a string, but my server would return an error like:

{"tags":["Incorrect type. Expected pk value, received str."]}

My json on the server is formatted like this

{"id":1, 
 "tags" : [
           {"id":1}, 
           {"id":2}
          ]
}

and in android studio I am trying to put in an ArrayList of integers that contain the tags id's like this

okhttp3.RequestBody fileRequestBody =  RequestBody.create(MediaType.parse("text/csv"), file); 

okhttp3.RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("id", projecID)
                        .addFormDataPart("tags", tagIDArray")
                        .addFormDataPart("file", "file", fileRequestBody).build();
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Torched90
  • 305
  • 1
  • 3
  • 18

2 Answers2

2

So I have figured it out, and I am going to post an answer if anyone comes across this in the future.

Very simply, you can iterate through the array of integers and add each one into the MultipartBody.Builder via .addFormDataPart("tags", tagIDArray.get(i)) where i is the index. Here is working code that I have now used in my project.

o

okhttp3.MultipartBody.Builder requestBodyBuilder = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("id", projecID)
.addFormDataPart("file", "file", fileRequestBody");

for(int i=0; i<tagIDdArray.size(); ++i){
    requestBodyBuilder.addFormDataPart("tags", tagIDArray.get(i));
}

RequestBody requestBody = requestBodyBuilder.build()

And then you can use the requestbody normally in your request and it will work as an array

Torched90
  • 305
  • 1
  • 3
  • 18
  • but addFormDataPart requires String as a value, not integer - I have the problem where server expects int so addFormDataPart doesn't work here unfortunately. Any ideas of how to workaround that to pass exactly int? – vir us Oct 26 '18 at 17:45
  • Found this answer https://stackoverflow.com/a/47627526/1767167 to allow you to pass primitive types. – zeenosaur Nov 04 '19 at 01:22
1

Post Request in form data allow only two types of values - Text and File.

enter image description here)

Hence there is no need to check for integers. Also if needed please read the correct way to send multipart request with form text data and a image file Retrofit way in Android

taranjeetsapra
  • 524
  • 7
  • 19