No able to send raw json in retrofit - android

I have been trying to send raw json using retrofit 2 but not working, i have tried JsonObject , map but it's not working at all. I don't understand what the problem is. Works fine on Postman.
I am trying to send this request:
{
"incomes":[{"amount":"5566","incomeId":"345"}]
}
my android code is:
#Headers({"Accept: application/json"})
#POST("/api/v1/addIncome")
Call<ResponseBody> addIncome(#Body Map<String, String> params);
Map<String, String> params = new HashMap<>();
Call<ResponseBody> req = null;
Income[] incomes = new Income[1];
incomes[0] = income;
params.put(URLParam.INCOMES, new Gson().toJson(incomes));
req = CustomUtil.getCuumiAPIObject(this, URLConstant.BASE_URL).addIncome(params);
I know added the relavent part, rest works fine with other services, problem is of parameter.In response server gives a null value exception meaning, the parameter their is not picking up the value. Would really appreciate some help.

While sending String Map, You need to send it with #FieldMap instead of String Map as #Body.
Use #FiledMap as below in your code:
#FieldMap Map<String, String> params
Edit
If you want to send your json with #Body, you need to send with pojo class as #Body by setting your value in pojo class.
Pojo class:
public class Incomes {
#SerializedName("incomes")
#Expose
private List<Income> incomes = null;
public List<Income> getIncomes() {
return incomes;
}
public void setIncomes(List<Income> incomes) {
this.incomes = incomes;
}
public class Income {
#SerializedName("amount")
#Expose
private String amount;
#SerializedName("incomeId")
#Expose
private String incomeId;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getIncomeId() {
return incomeId;
}
public void setIncomeId(String incomeId) {
this.incomeId = incomeId;
}
}
}
Then you need to create object of Incomes class and need to set every income in created object of Incomes class.
Incomes incomes=new Incomes();
Incomes.Income mIncome=new Incomes().new Income();
mIncome=income;
incomes.setIncomes(mIncome);
Then send Incomes class object as #Body in you API request.
req = CustomUtil.getCuumiAPIObject(this, URLConstant.BASE_URL).addIncome(incomes);
You also need to change your addIncome method as below:
Call<ResponseBody> addIncome(#Body Incomes incomes);
Hope this helps you.

Related

Need to post JSON as an array of objects via Retrofit while dynamically adding objects

I have to post a JSON Array of objects. The JSON sample is pasted below:
[
{
"checklistkey": "what is your age ___ and ur bd___",
"checklistvalue": "yes",
"taskId": "PMTASK-cmms-01-71-1"
},
{
"checklistkey": "how r you___? ______",
"checklistvalue": "no",
"taskId": "PMTASK-cmms-DE01-71-1"
}
]
The number of object here will be added dynamically based on the ID received in the previous request.
Now the POJO for this looks like:
public class CheckListAddRequest {
#SerializedName("taskId")
#Expose
private String taskId;
#SerializedName("checklistkey")
#Expose
private String checklistkey;
#SerializedName("checklistvalue")
#Expose
private String checklistvalue;
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getChecklistkey() {
return checklistkey;
}
public void setChecklistkey(String checklistkey) {
this.checklistkey = checklistkey;
}
public String getChecklistvalue() {
return checklistvalue;
}
public void setChecklistvalue(String checklistvalue) {
this.checklistvalue = checklistvalue;
}
public CheckListAddRequest(String taskId, String checklistkey, String checklistvalue) {
this.taskId = taskId;
this.checklistkey = checklistkey;
this.checklistvalue = checklistvalue;
}}
The Retrofit call for this is:
#POST("cmms")
#Headers("Content-Type: application/json")
Call<CheckListAddResponse> getCheckListAdd(#Body CheckListAddRequest checkListAddRequest,
#Header("X-Auth-Token") String token,
#Header("workspace") String workspace);
Now while added the details for creating a JSON request, I write something like:
CheckListAddRequest checkListAddRequest = new CheckListAddRequest(taskNumber, checkDesc, statusString);
Now if I have more than one object in the request, how can I send it?
This should be an array/list if its multiple and dynamic objects, you can easily change items add or remove from List and send
ArrayList< CheckListAddRequest >.
make this minor change.
#POST("cmms")
#Headers("Content-Type: application/json")
Call<CheckListAddResponse> getCheckListAdd(#Body ArrayList<CheckListAddRequest> checkListAddRequest,
#Header("X-Auth-Token") String token,
#Header("workspace") String workspace);
now pass the value in array list or list.

Retrofit,Dynamic json whose fields change depending on the parameters into Gson

I'm using retrofit2 and I need to call an API for information. The JSON that the API gives me has dynamic fields which change depending on the parameter values.
Note that I can have any number of parameters. Below is the JSON for the parameters "1","2".
{
"data":{
"1":{
"logo":"https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
"id":1,
"name":"Bitcoin",
"symbol":"BTC",
"description":"Bitcoin (BTC) is...",
"date_added":"2013-04-28T00:00:00.000Z",
"platform":null,
"category":"coin"
}
},
"2":{
"logo":"https://s2.coinmarketcap.com/static/img/coins/64x64/1.png",
"id":1,
"name":"Bitcoin",
"symbol":"BTC",
"description":"Bitcoin (BTC) is...",
"date_added":"2013-04-28T00:00:00.000Z",
"platform":null,
"category":"coin"
}
}
I've created an interface in which I get the header and the parameter key which then I call later in retrofit to return me the info I need.
public interface CurrencyService {
#GET(ApiConstants.CRYPTOCURRENCYINFO)
Call<CurrencyService> getCurrencyById(#Header("X-CMC_PRO_API_KEY")
String appkey,
#Query("id") int[] ints);
}
public class CurrencyService {
Map<String, Data> data;
}
public class Data {
String logo;
int id;
String name;
String symbol;
String description;
String date_added;
Object platform;
String category;
}
Call<CurrencyService> getCurrencyById(#Header("X-CMC_PRO_API_KEY")String appkey, #Query("id") int[] ints);

How do you parse json object inside a json array?

I am pretty weak with JSON, and probably have a silly question, and was wondering how to parse a JSON object placed inside a JSON array.
So, as of now, I have
public Single<Profile> doProfileApiCall() {
return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
.addHeaders(mApiHeader.getProtectedApiHeader())
.build()
.getObjectSingle(Profile.class);
To retrieve my profile params, but in my endpoints I have :
[{"Name": "this", "Email","that#gmail.com"}]
I have my endpoint set up as :
public static final String ENDPOINT_PROFILE =
BuildConfig.BASE_URL
+ "/linktojson";
which gives me the above JSON.
but the issue is the [], how do I modify this with :
public Single<Profile> doProfileApiCall() {
return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
.addHeaders(mApiHeader.getProtectedApiHeader())
.build()
.getObjectSingle(Profile.class);
such that I can use my profile.java model class which has
public class Profile {
#Expose
#SerializedName("Name")
private String name;
#Expose
#SerializedName("Email")
private String email;
etc...
}
Any idea how to go about this?
In the doProfileApiCall() method instead of .getObjectSingle use
.getJSONArraySingle(ProfileList.class)
Now create a new class ProfileList.java with the following code.
List<Profile> profileList = new ArrayList<>();
public List<Profile> getProfileList() {
return profileList;
}
public void setProfileList(List<Profile> profileList) {
this.profileList = profileList;
}
Change the returntype of the doProfileApiCall method to
public Single<ProfileList> doProfileApiCall()
Whenever you want to access the data use it with the list position 0, when in future you get more data, you can index the data accordingly.
Generally, if JSON root object is an array you should use List on Java side. In your case you have array so use related method:
return Rx2AndroidNetworking.post(ApiEndPoint.ENDPOINT_PROFILE)
.addHeaders(mApiHeader.getProtectedApiHeader())
.build()
.getObjectListSingle(Profile.class);
Rx2ANRequest source.

How can i post data with classname in Retrofit

I post data with retrofit my webservice but it return null because of i post like this;
{"username":"asd","password":"123"}
but i want to post like this;
{user:{"username":"asd","password":"123"}}
These are my entities and calling methods;
public class User {
#SerializedName("username")
#Expose
public String username;
#SerializedName("password")
#Expose
public String password;
}
My call service interface like this;
#POST("/test/Logon")
Call<Result> getLogon(#Body User user);
I don't want to use extra class for passing User on it.
Try this
#POST("/test/Logon")
Call<Result> getLogon(#Body Map<String,Object> user);
And white passing object to getLogon
Map<String,Object> map = new HashMap();
map.put("user",userObject);
getLogon(map)

Android Retrofit2 need to send request as Key-value but the value is a json, is it possible

Like here json is the key and the value part is a json,
how to achieved this?
json:{"id": "1234","services": [{ "service_id": "123","name": "abc"},"service_id": "123","name": "abc"}] }
I might be missing something but I think following should be sufficient (assuming you have retrofit configured to use gson converter).
public class MyPojo {
private String id;
private List<Map<String, String>> services;
...
}
For sending request parameters in key value pairs use HashMap.
Here your HashMap would be like this.
HashMap< String,Object> hashMap = new HashMap<>();
hashMap.put("json",YourPojo);
YourPojo.java
public class YourPojo{
private String id;
private List<Services> services;
//other fields
//getters and setters
//Inner class
public class Services{
public String service_id;
public String name;
//Getters and setters
}
}
and then put your hashmap as a request parameter in retrofit.
Hope this helps!.

Categories

Resources