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.
Related
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.
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.
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!.
here is my jsonString:
{
"status":1,
"data":[
{
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
},
{
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
}
],
"message":""
}
here is my receivingClass:
public class mAnswer{
#SerializedName("status")
public int mEnterStatus;
#SerializedName("data")
public List<Data> dataList;
public class Data {
#SerializedName("id")
public int mUserId;
#SerializedName("friendsInfo")
public GetUserDetails getUserDetails;
public class GetUserDetails{
#SerializedName("email")
public int email;
#SerializedName("phone")
public String phone;
#SerializedName("language")
public String language;
}
}
}
and here is my code for successful receiving answer where I am trying to save this data to SQLite db:
private void saveList(){
Vector<ContentValues> cVVector = new Vector<ContentValues>();
int arraySize = mAnswer.dataList.size();
for (int i = 0; i < arraySize; i++){
// **HERE IS PROBLEM**
cVVector.add(friendsValue);
}
if (arraySize > 0 ){
ContentValues[] cvArray = new ContentValues[arraySize];
cVVector.toArray(cvArray);
mContext.getContentResolver().
bulkInsert(J4D_DB_Contract.UserFriendsEntry.CONTENT_URI, cvArray);
}
}
So here is my problem:
how to correct call #SerializedName elements when i am trying to save List data to db?
any ideas?
Will be glad any help! Thanks!
mAnswer.dataList.get(0);
gives back the
"id":"39",
"friendsInfo":{
"email":"test#gmail.com",
"phone":null,
"language":"en"
}
this is what you should say in the loop:
mAnswer.dataList.get(0).getFriendsObject().getEmail();
mAnswer.dataList.get(0).getFriendsObject().getPhone();
I would use this site to generate my POJO, beucase it`s more cleaner I think.
http://www.jsonschema2pojo.org/
This site gives back well defined POJO architecture, what is ready for use.
Just set that you are working with JSON instead of JSON Scheme and using GSON (if you are using retrofit).
After you can copy your java files to your workplace.
You don't need the #SerializedName("jsonName") if the variable has the same name private String jsonName;
"tipolistView.setAdapter(listViewArrayAdapter)Is it possible to sort a JsonArray by a key?
I mean, I have a listview , and it is being created this way:
{"id":"1","nome":"glamourhood","tipo":"1"},
{"id":"2","nome":"Face da Mia","tipo":"2"},
{"id":"5","nome":"Team Transformerz","tipo":"3"},
{"id":"6","nome":"Face da Team de novo","tipo":"4"},
{"id":"7","nome":"Tiago Faria Fitness","tipo":"5"},
{"id":"8","nome":"Nuno Soares","tipo":"6}
And I wanted it sorted by "tipo" from smaller to bigger, or even better : by type * id (that would be awesome).
Is this achievable on Android?
deserialize your json into objects, like
(assumed these are movie titles)
#Serializable
public class Movie {
private int id;
#SerializedName("nome")
private String name;
private int tipo;
public Movie();
//getter & setter
}
For deserializing you could use GSON for instance. I've added an example for mapping json fields to different fields in an object (nome and name) when using GSON.
I can't come up with code for deserializing right now, but you will find plenty sources on the web. It must be somethiong like:
final Movie movie = gson.fromJson(yourJsonInputReader, Movie.class);
After deserializing those JSONs to objects, you may have a List<Movie> movies. Now you could sort this list in any way you want, use a CustomCoparator for this purpose.
public class MovieComparator implements Comparator<Movie>{
public enum Field {
ID, TIPO;
}
private Field field;
public MovieComparator(Field field) {
this.field = field;
}
#Override
public int compare(Movie mov1, Movie mov2) {
int comparison = 0;
switch(field) {
case ID:
comparison = mov1.getId().compareTo(mov2.getId());
case TIPO:
comparison = mov1.getTipo().compareTo(mov2.getTipo());
}
return comparison;
}
Then use it like:
Collections.sort(movies, new MovieComparator(MovieComparator.Field.ID));
Let me know if this works out or not, can't check it, because spending time with my son ;)