I have a json that looks like this
{"abcd": {
"id": 1234,
"response": "authenticated",
"key": "abrakadaba",
"userId": 5555
}}
and a class that looks like this:
public class Login
{
#SerializedName("response")
public String response;
#SerializedName("userId")
public int userId;
#SerializedName("id")
public int employeeId;
#SerializedName("key")
public String key;
}
This normally works, but not with a json that has the {"abcd": {}} before all the info i need to retrieve.
how do I handle this `"abcd" tag to find and serialize all the other values.
You'll need something to wrap the Login to coincide with the "abcd". gson/jackson/whatever is going to want to parse that first. You could create a new class that contains a Login. If that wrapper class is truly going to be throw-away then you may want to just have it parse a Map<String, Login> and then do a myParsedMap.get("abcd") to get your Login object.
here is what worked:
#SerializedName("auth")
authorization auth;
public class authorization
{
#SerializedName("response")
public String response;
#SerializedName("userId")
public int userId;
#SerializedName("Id")
public int employeeId;
#SerializedName("key")
public String key;
}
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'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);
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;
I can't seem to wrap my head around how to setup my class hierarchy for JSON conversion using GSON.
My JSON looks like:
{
"Users": {
"id": 1,
"name": "Jim",
"location": "Huntsville"
}
}
My User List class looks like:
public class UserList {
public static List<User> Users;
#SuppressWarnings("static-access")
public void setUserList(List<User> userList){
this.Users = userList;
}
public List<User> getUserList(){
return Users;
}
}
and lastly a user class that looks like this:
public class User {
private int id;
private String name;
private String location;
public int getId(){
return id;
}
public String getName(){
return name;
}
public String getLocation(){
return location;
}
public String toString(){
return("User: [id=" + id + "], [name=" + name + "], [location=" + location + "]");
}
}
Anyone mind giving me a shove in the right direction? I'd appreciate it!
EDIT:
Forgot to show my parsing code.. (Just reading a sample JSON file from SDCard)
BufferedReader br = new BufferedReader(new FileReader(Environment.getExternalStorageDirectory() + "/user.json"));
UserList userList = gson.fromJson(br, UserList.class);
are you sure your example JSON is correct?
It does not seem to be a list of things, just one user is defined.
Furthermore, your getter and setters for Users, should be following the get/set pattern and be called
public List<User> getUsers()
public void setUsers(List<User> users)
Also, you can follow the Java convention of small case and instruct Gson to use a different casing.
Assuming that you only have one entry of Users in your JSON. This would let you parse the snippit you provided, if you change the Users property into User not a list.
#SerializedName("Users")
private User user;
So if you want a list of users you should find that in the json, this should let you parse it as a list, !note that you need to have objects, which are enclosed, like:
{"users" : [{id:"one"}, ...]}
As pointed out in the comments.