In my application I want send some data to server and for this I used Retrofit library.
I should send data such as below:
{
"hours": ["22:05","19:57"]
}
I write below codes for Api services:
#POST("profile")
suspend fun postSubmitDrug(#Header("Authorization") token: String, #Body body: RequestBody):Response<ProfileData>
And write below codes info fragment for send data to server:
private lateinit var requestBody: RequestBody
var hourMinuteList = mutableListOf<String>()
val multiPart = MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("_method", "post")
multiPart.addFormDataPart("hours[]", parentActivity.hourMinuteList.toString())
requestBody = multiPart.build()
But send this list such as below:
{
"hours": [22:05,19:57]
}
How can I fix it and send list of string to server?
Use com.google.gson, and when you create your retrofitCLient call .addConverterFactory(create(GsonBuilder()))
create data model, ex:
data class RequestBody(
val hours: ArrayList<String>? = null
)
and just call your endpoint
#POST("profile")
suspend fun postSubmitDrug(#Header("Authorization") token: String, #Body body: RequestBody):Response<ProfileData>
and this is all, gson will automatically serialize your data to json
Related
I am using retrofit for posting data to server as below
#POST("web_php/app_user_login")
suspend fun loginApi(#Body body: RequestBodies.LoginRequestBody): Response<LoginResponse>
data class LoginRequestBody(
val user_name: String,
val user_password: String
)
But I want to post JSON Object directly just like as below
data class CreateAuditRequestBody(
val auditJsonObject: JSONObject
)
#POST("web_php/create_first_audit")
suspend fun createAuditApi(#Body body: RequestBodies.CreateAuditRequestBody): Response<CreateAuditResponse>
But It gives an error. Kindly Help me.
Thanks
This question already has answers here:
How to POST raw whole JSON in the body of a Retrofit request?
(27 answers)
Closed 9 months ago.
body format , that I want to send to rest api server :
for sending nested json with retrofit , must use #Body annotation in api interface, for above JSON :
first make a data class for your hole JSON :
data class YourJSON (#SerializedName("data")
var data : String,
#SerializedName("data2")
var data2: Data2 ,
)
then make a data class for another object inside the JSON :
data class Data2 (#SerializedName("obj")
var obj: String,
#SerializedName("obj1")
var obj1: String ,
#SerializedName("obj2")
var obj2: String ,
#SerializedName("obj3")
var obj3: Int
)
then make an interface class :
interface ApiService {
#POST(/api/your/url)
fun sendData(
#Body yourJson : YourJSON,
): Observable <yourResponse> }
I do a post request to Firebase push notifications:
#FormUrlEncoded
#POST("https://fcm.googleapis.com/fcm/send")
suspend fun createPushNotifications(
#Header("Authorization") Authorization: String,
#Field("to") to: String,
#Field("data") data: String
): Response<ResponseBody>
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl(urlApp)
.addConverterFactory(GsonConverterFactory.create())
.build()
// Create Service
val service = retrofit.create(notificationAPI::class.java)
var data:String = "{\"body\":\"value\",\"title\":\"Collapsing A\"}"
// Do the POST request and get response
val response = service.createPushNotifications(FireBaseKey,deviceId, data)
Question : I get back a wrong format data payload
Message
data payload:{data={"body":"value","title":"Collapsing A"}}
But what i need is a payload in this format:
{data: {"body":"value","title":"Collapsing A"}}
Guess, I'm already baffled with what I'm doing, so I'm reaching out to the community.
I have the following:
UserModel
data class UserModel(
val id: String,
val name: String
){}
UserService
#Headers("Accept: application/json")
#POST("register")
fun doRegisterUserTest(
#Query("user_id") userName: String,
#Query("password") passWord: String
): Deferred<UserModel>
UserRepository
fun test(username: String, password: String): List<UserModel>{
Network.createNetworkRequest().create(UserService::class.java).doRegisterUserTest(username, password)
val x: UserService by lazy {Network.createNetworkRequest().create(UserService::class.java)}
val y = x.doRegisterUserTest(username, password)
return y
}
UserViewModel
private val _result = MutableLiveData<List<UserModel>>()
val result: LiveData<List<UserModel>> = _result
fun onRegister(username: String, password: String) {
viewModelScope.launch {
// connect to api server
//_registrationStatus.value = RegistrationStatus.LOADING
try {
_result.value = userRepository.test(username, password)
....
}
}
}
Network Client
private val moshi = Moshi.Builder()
.add(KotlinJsonAdapterFactory())
.build()
/**
* Main entry point for dto access. Call like `Network.devbytes.getPlaylist()`
*/
object Network {
fun createNetworkRequest(): Retrofit {
// Configure retrofit to parse JSON and use coroutines
val retrofit = Retrofit.Builder()
.baseUrl("http://10.0.2.2:8081/api/")
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
return retrofit
}
}
In my api, the above (in ideal scenario) will yield the following:
{
"user": [
{
"user_sys_id": 0,
"name": "Blah blah",
}
]
}
I want to read the values from _result.value = userRepository.test(username, password), I presume that test function will return a List> but I don't know how to access the members.
How can I check _result for the values of user_sys_id and name?
How come I'm getting the following (if I convert the response straight to a List)
Unable to create call adapter for Xmodel for method UserService.doRegisterUserTest
Am I missing something?
Likewise, is it fine to do a Retrofit Call if you were already using Coroutines?
From this Unable to create call adapter for retrofit2.Response<...>, it seems that the function should be suspended, but if I do that I would get a warning
Redundant suspend modifier
PS. Although, if I follow repository pattern, I'm able to see that results where written on a local database the values retrieved from the API, however, I don't think that is correct to store data that aren't supposed to be stored in the first place, say for eg. in a Registration, if the registration fails you just want to read the error message directly from the response
I'm trying to post some data with retrofit 2 but I'm gettins some problems... and don't find any example like this...
This is the body that I have to send:
{
"birthday": "12-01-1987",
"name": bob,
"activity": {
"activity_preferences": {
"user_subjects": [4,7,8],
"user_allergies": [1,6,10],
}
}
}
This is my data class:
data class GenericFormDataEntity(
var birthday: String,
var name: String,
#SerializedName("activity")
var food: ActivityEntity?
)
data class ActivityEntity(#SerializedName("activity_preferences")val activityPreferences: ActivityPreferencesEntity)
data class ActivityPreferencesEntity(#SerializedName("user_Subjects")var userSubjects:List<Int>?,#SerializedName("user_allergies")var userAllergies: List<Int>?)
This is the method that I'm trying to build the json:
fun getUserFormEntity(): String{
val paramObject = JSONObject()
paramObject.put("birthday", birthday)
paramObject.put("name", name)
paramObject.put("activity", getActivityEntity())
return paramObject.toString()
}
private fun getActivityEntity(): ActivityEntity{
return ActivityEntity(ActivityPreferencesEntity(selectedSubjectList, selecteAllergiesList))
}
And this is the json that is returning me:
{\"birthday\":\"23-12-2019\",\"name\":Bob,"activity\":\"ActivityEntity(activity_preferences=ActivityPreferencesEntity(user_Subjects=[4,7,8], user_allergies=[1,6,10])"}"
My question is, how can I get the correct json that I have to send as a body:
#Headers("Accept: application/json")
#POST("xxxxxxxx")
suspend fun saveUserData(#Body userFormData: String)
You need to stringify getActivityEntity using Gson.
Gson.toJson(getActivityEntity())
Also, from your API I infer that you are using retrofit why not pass along the entire instance of GenericFormDataEntity as the body for your API.
For enabling this you need to follow by adding GsonConverterFactory.create(gson) to your retrofit.
Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create(gson))
.callFactory(okHttpClient)
.build()