How to upload multiple image files with JSON to server from android?

250 Views Asked by At

I have to upload multiple images included in JSON from android.

{
       "topicId" : 1,
       "QuizTest": [
            {
                "question": "This first question for test",
                "Image" : "file:///D:/Images/fb_logo.png",
                "isTrue" : 3,
                "OptionFor":
                    {
                        "1" : "i am option 1",
                        "2" : "i am option 2",
                        "3" : "i am option 3",
                        "4" : "i am option 4"
                    }
                
            },
            {
                "question": "This second question for test",
                "Image" : "",
                "isTrue" : 2,
                "OptionFor": 
                    {
                        "1" : "i am  2 option 1",
                        "2" : "i am 2 option 2"
                     }
                
            },
            {
                "question": "This third question for test",
                "Image" : "file:///D:/Images/icon.png",
                "isTrue" : 1,
                "OptionFor": 
                    {
                        "1" : "i am 3 option 1",
                        "2" : "i am 3 option 2",
                        "3" : "i am 3 option 3",
                        "4" : "i am 3 option 4",
                        "5" : "i am 3 option 5"
                     }
                
            }
        ]
}

I have data like this to upload.

I have tried with a volley, android networking. But I am not sure if I can upload files like this.

I have uploaded with json in body. Doesn't work. Please help.

1

There are 1 best solutions below

5
On BEST ANSWER

You can use Retrofit for API calls where you can send payload as @Body or however required by API provider. You can set Gson converter in Retrofit builder so that you don't have to write plain Json objects.

If you are using Kotlin, you can write data classes like below

data class Options(
  val 1: String,
  val 2: String,
  val 3: String,
  val 4: String,
  val 5: String 
)
data class Question(
  val question: String,
  val Image: String,
  val isTrue: Int,
  val OptionFor: Options
)
data class Test(
  val topicId:Long,
  val QuizTest: Questions
)

And then you can send them as payload in API call

@POST("{api_end_point}")
fun sendData(@Body test: Test)