Reputation: 970
How can I create dynamic model based on the response of the JSON? I have a response where there are number of fields in which there are some fields are string and some of them are boolean. For Example
Suppose, a user have their own data like id, name, city, phone, address etc. Sometimes when user optional fields is phone or city or address then might he/she didn't enter while they register.
When I get the list of the user's the optional fields like city or phone is false(boolean) if user's not entered while they were signup or register. Similarly, when some user entered while they were registering. For example user no 1 have all the information id, name, city, phone and address while he/she registering. When I get the list of the user's particular object of the JSON will come's up with the value like "phone":"123567980", "email":"[email protected]".
So what I will try to create is dynamic model based on the whatever the value's come in any of the datatype it's will handle while parsing those data in java?
See the difference between objects
{
"id": 3,
"name": "Administrator",
"email": "[email protected]",
"phone": false,
"street": false,
"city": false,
"state_id": false,
"country_id": false
},
{
"id": 1,
"name": "Quadrastores",
"email": "[email protected]",
"phone": "+965 99964854",
"street": "Shop 29, Qairawan complex, Ibn khaldoun St. Hawalli",
"city": "Kuwait",
"state_id": false,
"country_id": [
122,
"Kuwait"
]
},
Am I on the correct way please suggestion or example of it if it's possible to do so.
Upvotes: 0
Views: 201
Reputation: 1609
In my opinion what you can do is you can use 'Object' or 'Any' as the type, and then use is
or instanceof
to check the type and create the model properly. But it will be neverending story with type casting and checking:
{
"id": Int,
"name": String,
"email": String,
"phone": Object,
"street": Object,
"city": Object,
"state_id": Object,
"country_id": Object
}
What you can do is to create your second model with proper tpes, and just transform the one incoming from API to it:
API model:
{
"id": Int,
"name": String,
"email": String,
"phone": Object,
"street": Object,
"city": Object,
"state_id": Object,
"country_id": Object
}
Your Model:
{
"id": Int,
"name": String,
"email": String,
"phone": String?, // nullable,
"street": String?, // nullable,
"city": String?, // nullable,
"state_id": Int?, // nullable,
"country_id": List<Any>?, // nullable
}
And in the code:
String jsonString = yourJsonAsString;
YourModel model = new YourModel();
JSONObject json = new JSONObject(jsonString);
Object phone = json.get("phone");
if(phone instanceof String){
model.setPhone(phone.toString());
} else {
model.setPhone(null);
}
And so on
Upvotes: 1