Hi i'm trying to learn android and now implementing the retrofit 1.9 for my rest POST and GET request can somebody help me on how to model given json objects and strings? im very confused on some tutorials I have learned how make a pojo for this json object
{
"contacts": [
{
"id": "c200",
"name": "Ravi Tamada",
"email": "ravi#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
},
{
"id": "c201",
"name": "Johnny Depp",
"email": "johnny_depp#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
}}]}
Using this model
Contacts.class
public class Contacts {
#SerializedName("contacts")
#Expose
private List<Contact> contacts = new ArrayList<Contact>();
public List<Contact> getContacts() {
return contacts;
}
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
and Contact.class for the objects
public class Contact {
#SerializedName("id")
#Expose
private String id;
#SerializedName("name")
#Expose
private String name;
#SerializedName("email")
#Expose
private String email;
#SerializedName("address")
#Expose
private String address;
#SerializedName("gender")
#Expose
private String gender;
public String getId() {return id;}
public void setId(String id) {this.id = id;}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getEmail() {return email;}
public void setEmail(String email) {this.email = email;}
public String getAddress() {return address;}
public void setAddress(String address) {this.address = address;}
public String getGender() {return gender;}
public void setGender(String gender) {this.gender = gender;}}
And Calling the list using this on my MainActivity.class
private void getContacts() {
final ProgressDialog loading = ProgressDialog.show(this, "Fetching Data", "Please wait...", false, false);
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(ROOT_URL).build();
ContactsAPI api = adapter.create(ContactsAPI.class);
api.getContacts(new Callback<Contacts>() {
#Override
public void success(Contacts contacts, Response response) {
loading.dismiss();
List<Contact> contactList = contacts.getContacts();
String[] items = new String[contactList.size()];
for (int i = 0; i < contactList.size(); i++) {
items[i] = contactList.get(i).getName();
}
ArrayAdapter adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.simple_list,R.id.textview, items);
//Setting adapter to listviesw
listView.setAdapter(adapter);
}
#Override
public void failure(RetrofitError error) {
}
});
}
THen my Question is how should i make a model out of this array Object?
{
"-KNea90tV5nZlkeqxc3Q": {
"accountName": "Mark Papyrus",
"accountNumber": "12435656443",
"accountType": "Peso Savings"
},
"-KNeaPmBoTXV4mQC6cia": {
"accountName": "Mark Dremeur",
"accountNumber": "12435656444",
"accountType": "Peso Checking"
}
i found it confusing how to make models and difference of given json arrays pls guide me thanks.
I think me and you are having the same problems but I am stuck so I can help you as far as I can . First you cannot use jsonschema2pojo.org to create the pojo class you need to use hashmap from what I understand "-KNea90tV5nZlkeqxc3Q": is a key but 1 of the classes should be the following ( also the accountype since its a type you can use enum but it would be bit harder to code)
public class Account {
private String accountName;
private String accountNumber;
private String accountType;
public Account() {
}
public String getAccountName() {return accountName;}
public void setAccountName(String accountName) {
this.accountName=accountName;}
// *** repeat for the accountnumber and accountype
}
if the key "KNea90tV5nZlkeqxc3Q" is dynamic and need to capture them, you musto to use a hashmap in your model to catch them correctly.
check this issue it could be useful:
Parse Dynamic Key Json String using Retrofit
Related
De-Serializing Objects within a List
I currently have an 'Admin' Entity in which upon a GET Request of AllAdmin() will return me the following response. This was used in Postman.
GET Response for AllAdmin() [POSTMAN]
[
{
"adminId": 1,
"fullName": "Patrick ",
"email": "patrick#gmail.com",
"dob": "1669-12-12",
"mobileNumber": "96369636",
"password": "password123!",
"usages": [
{
"id": 3,
"datetimeUnlocked": "2021-06-07 10:12:23"
},
{
"id": 4,
"datetimeUnlocked": "2021-06-07 10:12:27"
}
],
"authorization": [
{
"id": 2,
"datetimeAccepted": "2021-06-07 10:12:14"
}
],
"adminAllow": []
},
{
"adminId": 2,
"fullName": "Worker ",
"email": "worker#gmail.com",
"dob": "2000-12-12",
"mobileNumber": "96399639",
"password": "password123!",
"usages": [],
"authorization": [],
"adminAllow": []
} ]
The current code is my Admin Model in my Android Application.
Admin.java Model Class
public class Admin {
#SerializedName("adminId")
private long adminID;
#SerializedName("fullName")
private String adminFullName;
#SerializedName("email")
private String adminEmail;
#SerializedName("dob")
private String adminDOB;
#SerializedName("mobileNumber")
private String adminMobileNumber;
// Constructor
public Admin(long adminID, String adminFullName, String adminEmail, String adminDOB, String adminMobileNumber) {
this.adminID = adminID;
this.adminFullName = adminFullName;
this.adminEmail = adminEmail;
this.adminDOB = adminDOB;
this.adminMobileNumber = adminMobileNumber;
}
// Getter
public long getAdminID() {
return adminID;
}
public String getAdminFullName() {
return adminFullName;
}
public String getAdminEmail() {
return adminEmail;
}
public String getAdminDOB() {
return adminDOB;
}
public String getAdminMobileNumber() {
return adminMobileNumber;
}
}
I would like to clarify on how I would de-serialize the usages and authorization properties so that I am able to access and manipulate the data entries for these?
I thank you in advance for your clarifications!
For usages, you should use a List<Usage> as the serializable. My assumption is you are using Retrofit. So the Retrofit Gson converter will take care of parsing the array of Usage. The same logic would apply for authorization. You can use the different key there for the datetimeAccepted case.
Check this sample for Usage
public class Usage {
#SerializedName("id")
#Expose
private Integer id;
#SerializedName("datetimeUnlocked")
#Expose
private String datetimeUnlocked;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDatetimeUnlocked() {
return datetimeUnlocked;
}
public void setDatetimeUnlocked(String datetimeUnlocked) {
this.datetimeUnlocked = datetimeUnlocked;
}
}
Your updated Admin class must look like this
public class Admin {
#SerializedName("adminId")
private long adminID;
#SerializedName("fullName")
private String adminFullName;
#SerializedName("email")
private String adminEmail;
#SerializedName("dob")
private String adminDOB;
#SerializedName("mobileNumber")
private String adminMobileNumber;
#SerializedName("usages")
private List<Usage> usages;
// Constructor
public Admin(long adminID, String adminFullName, String adminEmail, String adminDOB, String adminMobileNumber, List<Usage> usages) {
this.adminID = adminID;
this.adminFullName = adminFullName;
this.adminEmail = adminEmail;
this.adminDOB = adminDOB;
this.adminMobileNumber = adminMobileNumber;
this.usages = usages;
}
// Getter
public long getAdminID() {
return adminID;
}
public String getAdminFullName() {
return adminFullName;
}
public String getAdminEmail() {
return adminEmail;
}
public String getAdminDOB() {
return adminDOB;
}
public String getAdminMobileNumber() {
return adminMobileNumber;
}
public List<Usage> getUsages() {
return usages;
}
}
I am fetching some json from a pojo class using GSON and hashmap. This is Pojo Class
public class NetworkConfiguration {
#SerializedName("GUID")
#Expose
private String gUID;
#SerializedName("Name")
#Expose
private String name;
#SerializedName("Type")
#Expose
private String type;
#SerializedName("WiFi")
#Expose
private WiFi wiFi;
public NetworkConfiguration() {
}
public NetworkConfiguration(String gUID, String name, String type, WiFi wiFi) {
super();
this.gUID = gUID;
this.name = name;
this.type = type;
this.wiFi = wiFi;
}
public String getGUID() {
return gUID;
}
public void setGUID(String gUID) {
this.gUID = gUID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public WiFi getWiFi() {
return wiFi;
}
public void setWiFi(WiFi wiFi) {
this.wiFi = wiFi;
}
}
This is how I am trying to get JSON
WiFi wiFi = new WiFi();
wiFi.setPassphrase(open_network_configuration_wifi_password_edit.getText().toString());
wiFi.setSecurity(spinner_open_network_configuration_wifi_security.getSelectedItem().toString());
wiFi.setSSID(open_network_configuration_wifi_ssid_edit.getText().toString());
if (open_network_configuration_wifi_autoconnect_option.isChecked()) {
wiFi.setAutoConnect(true);
} else {
wiFi.setAutoConnect(false);
}
Map<String, Object> openNetworkConfigurationMap = new HashMap<>();
networkConfigurations.add(new NetworkConfiguration(open_network_configuration_guid_edit.getText().toString(),
open_network_configuration_name_edit.getText().toString(), "WiFi", wiFi));
Gson gson = new Gson();
String json = gson.toJson(networkConfigurations);
Map<String,Object> result = new Gson().fromJson(json, Map.class);
openNetworkConfigurationMap.put("NetworkConfigurations", json);
And this is what I am getting
NetworkConfigurations= [{
"GUID": "a",
"Name": "Example A",
"Type": "WiFi",
"WiFi": {
"SSID": "Example A",
"Security": "None",
"AutoConnect": true
}
}]
And this is wrong. This is what I am expecting
"NetworkConfigurations": [{
"GUID": "a",
"Name": "Example A",
"Type": "WiFi",
"WiFi": {
"SSID": "Example A",
"Security": "None",
"AutoConnect": true
}
}]
The main thing which is kinda worry that I am getting an equal sign = but it should be : after the NetworkConfigurations
Any kind of help would be appreciated. Thanks in advance
Just add this in the end:
String json = gson.toJson(openNetworkConfigurationMap);
and print the output json
I am making an app where I am using room as a database cache and fetching data from the server using retrofit2 and saving it in room database but after fetching from server data is unable to insert in room database.
Here is an exception it is showing:
This is my pojo class below:
#Entity(tableName = "Users")
public class User {
#NonNull
#PrimaryKey
#SerializedName("_id")
private String _id;
#ColumnInfo(name = "name")
#SerializedName("name")
#Expose
private String name;
#ColumnInfo(name = "age")
#SerializedName("age")
#Expose
private String age;
public User(){}
public User(#NonNull String _id,String name, String age) {
this._id = _id;
this.name = name;
this.age = age;
}
#NonNull
public String get_id() {
return _id;
}
public void set_id(#NonNull String _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
JSON Response
[
{
"id": "5cf68fe7b439470017236249",
"name": "Rhea",
"age": "2"
},
{
"id": "5d09006696a8470cbc7c34a2",
"name": "Don",
"age": "10"
},
{
"id": "5d092d9858af5d22a80858bf",
"name": "Roman",
"age": "30"
},
{
"id": "5d09e9976f3bad18b8fa54a0",
"name": "Roman",
"age": "30"
},
{
"id": "5d09ea2ac127bd07b4b64f6f",
"name": "Roman",
"age": "30"
}
]
Someone please let me know what is happening wrong. Any hep would be appreciated.
chnage
#NonNull
#PrimaryKey
#SerializedName("_id") // key does not match with response key
private String _id;
to
#NonNull
#PrimaryKey
#SerializedName("id")
private String _id;
It seems that you have the id parameter named as "id" in your JSON while your model is waiting for "_id". Try removing that leading underscore symbol.
I think that one or more users id that you are fetching data from the server using retrofit2 is null, and because of that you can't insert into your local database
Generated GSON JAVA classes from JSON Response. I am trying to parse the Address1 and Address from the Address_.java class. It was generated from the JSON response. I am using GSON to parse it and and trying read the value of Address1 and Address2 from it. I tried different ways to parse but attempt was not successful.
AddressList.java
public class AddressList {
#SerializedName("_embedded")
#Expose
private Embedded embedded;
public Embedded getEmbedded() {
return embedded;
}
public void setEmbedded(Embedded embedded) {
this.embedded = embedded;
}
}
Embedded.java
public class Embedded {
#SerializedName("address")
#Expose
private List<Address> address = null;
public List<Address> getAddress() {
return address;
}
public void setAddress(List<Address> address) {
this.address = address;
}
}
Address.java
public class Address {
#SerializedName("_links")
#Expose
private Links_ links;
#SerializedName("_embedded")
#Expose
private Object embedded;
#SerializedName("customer")
#Expose
private String customer;
#SerializedName("account")
#Expose
private String account;
#SerializedName("address1")
#Expose
private String address1;
#SerializedName("address2")
#Expose
private String address2;
public Links_ getLinks() {
return links;
}
public void setLinks(Links_ links) {
this.links = links;
}
public Object getEmbedded() {
return embedded;
}
public void setEmbedded(Object embedded) {
this.embedded = embedded;
}
public String getCustomer() {
return customer;
}
public void setCustomer(String customer) {
this.customer = customer;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
}
GSON RESPONSE
{
"_links": {
"self": {
"href": "https://xxxxx/xxx/address?where=xxx%20eq%20xx%20and%20customer%20eq%xxxx&page=1&pagesize=50"
}
},
"_embedded": {
"address": [
{
"_links": {
"self": {
"href": "https://xxxx/xxxx/xxxx/xxxx"
}
},
"_embedded": null,
"customer": "12345",
"account": "",
"address1": "111 ABC DR",
"address2": " ",
}
]
},
"totalItems": 1,
"pageSize": 50,
"totalPages": 1,
"currentPage": 1
}
Can someone please help me? Thanks
Thanks GhostCat. I removed the _embedded from the response and the object itself and it started working. It was third party webservices was sending the response with _. It's working now.
I have a String in my servlet which is of the following format.
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"bookName": [
"The Magic",
"The Power"
]
}
where the bookName is an array. I want to access the values in the array and populate in the bean. But, when I try to convert the string to jsonobject, I am getting the following exception because bookName is an array com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY This is how I am trying to do it
JSONObject js= new JSONObject();
String inputData= request.getParameter("inputData");
HashMap<String, String> hmap= new HashMap<String, String>();
Type type = new TypeToken<HashMap<String, String>>(){}.getType();
hmap = gson.fromJson(inputData, type);
js.putAll(hmap);
What I am doing is, I convert the string to a map and then add it to the JSONObject.
Since there are many json serializers and not sure which is the best. Right now, I have net.sf.json.JSONObject and com.google.gson.JsonObject
Can someone help me to get this solved.
Thanks in advance
You can map your JSON to a POJO.
If the book will have more attributes besides the name, you'll need two POJOs, as you can see below.
A POJO for the book:
class Book {
private String name;
private String author;
public Book() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
And a POJO for the shelf, which have a list of books:
class Shelf {
private String name;
private Integer noOfBooksRequired;
private String type;
private List<Book> books;
public Shelf() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNoOfBooksRequired() {
return noOfBooksRequired;
}
public void setNoOfBooksRequired(Integer noOfBooksRequired) {
this.noOfBooksRequired = noOfBooksRequired;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
Your JSON will look like this:
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"books": [
{"name": "The Magic", "author": "John Doe"},
{"name": "The Power", "author": "Jane Doe"}
]
}
And then you can use Gson to parse your JSON:
Gson gson = new Gson();
Shelf shelf = gson.fromJson(inputData, Shelf.class);
Update
Considering your JSON looks like this (the book can be represented as a String):
{
"name": "Jam",
"noOfBooksRequired": "2",
"type": "Type 1",
"books": [
"The Magic",
"The Power"
]
}
Only one POJO with a list of String is enough:
class Shelf {
private String name;
private Integer noOfBooksRequired;
private String type;
private List<String> books;
public Shelf() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getNoOfBooksRequired() {
return noOfBooksRequired;
}
public void setNoOfBooksRequired(Integer noOfBooksRequired) {
this.noOfBooksRequired = noOfBooksRequired;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getBooks() {
return books;
}
public void setBooks(List<String> books) {
this.books = books;
}
}