How to create POJO class for retrofit with dynamic keys names - android

I am sorry but i couldn't even phrase the question well but here it goes.
I am getting a JSON response like this:
{
"results": {
"b2bc01": [{
"message": "Successfully created",
"_id": "596c8b25ce2350e41600002f",
"status": "Success",
"code": 200
}],
"b2bc02": [{
"message": "Successfully created",
"_id": "596c8b25ce2350e416000030",
"status": "Success",
"code": 200
}]
.
.
.
"b2bc0n":[{
"message": "Successfully created",
"_id": "596c8b25ce2350e416000030",
"status": "Success",
"code": 200
}]
}
}
How do i create POJO class for this type of JSON. I tried in jsonschema2pojo but i feel its not a good result.
Please help. Thank in advance

Your POJO file
class MyPojo {
HashMap<String, ArrayList<MyModel>> results;
class MyModel {
String message;
String _id;
String status;
int code;
}

You can only use pojo with this data:
[{
"message": "Successfully created",
"_id": "596c8b25ce2350e41600002f",
"status": "Success",
"code": 200
}]
And if you use retrofit 2 and gson, I recommend you use interface JsonDeserializer
with .registerTypeAdapter()
Example
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.registerTypeAdapter(GpcProductDetail.class, new GpcProductDeserializer())
.create();
And parse manually that part of json.

Related

How to handle unknown response type with Retrofit

I am new to Retrofit and GSON
before retrofit, I have created a custom class for API calls, and map data manually.
This is my standard Response Type
{
"timestamp",
"status",
"message",
"payLoad",
"error"
}
If I GET the error from the server so my response is like
{
"timestamp":123456789,
"status":302,
"message":"Send All Data",
"error":"Partial Content"
}
If I get Success but Payload IS JSONObject so response like
{
"timestamp":123456789,
"status":200,
"message":"Save Successfully",
"payLoad":"{
"token": "...",
"userDetails": {
"id": 1,
"username": "...",
"firstName": "Deepak",
"lastName": "Gupta",
"gender": "MALE",
"address": ...,
"demoModel": {
"id": 1,
"demo": "enginner",
"demoConstant": "ENGINNER",
"active": true
},
"registrationDate": 1585831235533,
"enabled": true,
"expireTime": 4178010611915}
}
If I get Success but Payload IS JSONArray so response like
{
"timestamp": 1586330473808,
"status": 200,
"message": "SUCCESS",
"payLoad": [
{
...
},{
...
},{
...
}
]
}
I tried to make Payload to Object and then using InstanceOf I'll cast to respective model or List but then getting error linkedtreemap not cast to list or Object.

Android How to Deserialize the Json String Using Pojo Class

I Am getting this Json Response from server how to deseriallize the json string
{
"results": {
"status": "true",
"message": "Successfully Get Data",
"PdfData": {
"Pdf_Result": [{
"Pdf_File_Name": "aft.pdf",
"Subject_Name": "Maths",
"Subject_Id": "1",
"Chapter_ID": "M1111",
"Chapter_Name": "Relations and Functions",
"Downloaded": "YES"
}, {
"Pdf_File_Name": "date.pdf",
"Subject_Name": "Maths",
"Subject_Id": "1",
"Chapter_ID": "M1112",
"Chapter_Name": "Algebra",
"Downloaded": "YES"
}]
}
}
}
see jsonschema2pojo.org site and Gson library tutorial
https://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This tutorials will teach you how to parse with Json using Gson

android - Retrofit 2:Correct way of Parsing JSON with multiple arrays

I have started using retrofit:2.0.2 first time into my new project and I have done with first service call using retrofit but am not sure is it correct way or not here is what i have done
web services response
{
"status": true,
"message": "",
"data": {
"schools": [ { "id": "1", "name": "test 1" }, { "id": "2", "name": "test 12" }],
"referrals": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"Brands": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"Teams": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
"positions": [ { "id": "195", "name": "test 1" }, { "id": "1483", "name": "test 12" }],
}
}
created 3 model classes to map above response
public class SimpleObject {
int id;
String name;
// getter setter
}
public class SimpleData {
private List<SimpleObject> schools = new ArrayList<SimpleObject>();
private List<SimpleObject> referrals = new ArrayList<SimpleObject>();
private List<SimpleObject> positions = new ArrayList<SimpleObject>();
private List<SimpleObject> Teams = new ArrayList<SimpleObject>();
private List<SimpleObject> Brands = new ArrayList<SimpleObject>();
// getter, setter
}
public class ResponseData{
boolean status;
String message;
SimpleData data;
// getter setter
}
and then made a service call using Retrofit2
call.enqueue( new Callback<ResponseData>() {
#Override
public void onResponse(Call<ResponseData> call, Response<ResponseData> response) {
}
#Override
public void onFailure(Call<ResponseData> call, Throwable t) {
}
and its working fine but a want to insure that is it best way of doing this or can any one suggest the best way of handling such a response without creating multiple model classes for simple data (there should me only one model class "SimpleObject" and other will be list of "SimpleObject")
Please comment or suggest best way to handling response thanks.
The way you currently have it structured looks correct. You need to have one model for every nested level in the JSON response, which you have.
The only other option is simply breaking the object up using keys to pull all of the JSONObjects and JSONArrays, which I do not recommend.
copy and paste your json response in the link given below and download zip file and put it in your project directly.
This link will convert your any kind of json response and convert it into POJO

Retrofit POJO is null but JSON is valid

Have been scratching my head on this one. The JSON Response is a valid one:
{
"MRData": {
"xmlns": "http://ergast.com/mrd/1.4",
"series": "f1",
"url": "http://ergast.com/api/f1/current/2.json",
"limit": "30",
"offset": "0",
"total": "1",
"RaceTable": {
"season": "2014",
"round": "2",
"Races": [
{
"season": "2014",
"round": "2",
"url": "https://en.wikipedia.org/wiki/2014_Malaysian_Grand_Prix",
"raceName": "Malaysian Grand Prix",
"Circuit": {
"circuitId": "sepang",
"url": "http://en.wikipedia.org/wiki/Sepang_International_Circuit",
"circuitName": "Sepang International Circuit",
"Location": {
"lat": "2.76083",
"long": "101.738",
"locality": "Kuala Lumpur",
"country": "Malaysia"
}
},
"date": "2014-03-30",
"time": "08:00:00Z"
}
]
}
}
}
The POJO for the response:
public class ApiResponse {
MRData mrdata;
public class MRData {
String xmlns;
String series;
String url;
String limit;
String offset;
String total;
RaceTable raceTable;
}
}
The apiResponse object is always null. Anyone can point out what is wrong with the POJO object here?
Thanks.
I see a couple of potential issues here:
You are defining a class inside another class; I have never seen it done like this. You might want to separate in two different files.
Your variable names on your POJO should match the variable names on the JSON response exactly. For example:
public class ApiResponse {MRData MRData;}
If you want your POJO's variables to be different than what the JSON sends back, you should use #SerlizedName.

Gson ignore json field and deserialize

I'm working with android and gson and i was wondering if i can ignore a field from the webservice.
this its my gson object
Gson gson = new GsonBuilder().serializeNulls().create();
So what i need is to ignore validator field and deserialize to my custom bean in the following code.
Its any way to do that with gson ?
{ "posts":
[
{
"username": "John",
"message": "I'm back",
"time": "2010-5-6 7:00:34"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
,
{
"username": "Smith",
"message": "I've been waiting",
"time": "2010-4-6 10:30:26"
"validator":[{
"prog": "Name1",
"name": "Name2",
"computername": "Name3",
"date": "2010-11-20 19:39:55"
}]
}
]}
Thanks in advance
Cheers
You can call gson.fromJson(inputString, localObject) and if localObject doesn't declare a validator variable, it will just skip it.

Categories

Resources