How can i post data with classname in Retrofit - android

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)

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.

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.

No able to send raw json in retrofit

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.

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!.

MappingFacebook JSON response to POJO

I am making an API call to Facebook and receiving the following Json object:
{"first_name":"FirstName",
"last_name":"LastName",
"email":"email#email.com",
"picture":{"data":{"is_silhouette":true,"url":"pictureUrl"}},"id":"12345"}
Instead of deserializing the object manually, I am currently using Gson for it, like this:
FacebookProfileModel facebookProfileModel = new Gson().fromJson(object.toString(), FacebookProfileModel.class);
Here's how my POJO looks like:
#SerializedName("first_name")
String mFirstName;
#SerializedName("last_name")
String mLastName;
#SerializedName("email")
String mEmail;
#SerializedName("url")
String mUrl;
Obviously, I am receiving all the values except for the url, since the value is in 2 Json objects: picture and data. I guess one possible solution but not the best would be to create the Picture object within the Facebook Model and then the Data object within the Picture object but feels bad creating 2 more pojos for a String. Any other solutions?
There is no annotation based solution for this. However, the custom de-serializer would resolve this problem.
Custom Deserializer:-
public class FacebookProfileModelDeserializer implements JsonDeserializer<FacebookProfileModel> {
#Override
public FacebookProfileModel deserialize(JsonElement paramJsonElement, Type paramType,
JsonDeserializationContext paramJsonDeserializationContext) throws JsonParseException {
String url = paramJsonElement.getAsJsonObject().get("picture").getAsJsonObject().get("data").getAsJsonObject()
.get("url").getAsString();
FacebookProfileModel facebookProfileModel = new Gson().fromJson(paramJsonElement.getAsJsonObject(),
FacebookProfileModel.class);
facebookProfileModel.setmUrl(url);
return facebookProfileModel;
}
}
Main method:-
public static void main(String[] args) {
String jsonString = "{\"first_name\":\"FirstName\",\"last_name\":\"LastName\",\"email\":\"email#email.com\",\"picture\":{\"data\":{\"is_silhouette\":true,\"url\":\"pictureUrl\"}},\"id\":\"12345\"}";
Gson gson = new GsonBuilder()
.registerTypeAdapter(FacebookProfileModel.class, new FacebookProfileModelDeserializer())
.create();
FacebookProfileModel faceBookProfileModel = gson.fromJson(jsonString, FacebookProfileModel.class);
System.out.println(faceBookProfileModel.toString());
}

Categories

Resources