Serialize other fields in retrofit based on a field value - java

I am working on a json response with retrofit and it has a field named by type in price json object with 3 cases: free, static and dynamic.
in each case the response is like this:
1. static:
{
"status": 200,
"message": "Course Details Successful",
"data": {
"id": 204,
"title": "اصول حسابداری2",
"price": {
"type": "static",
"value": {
"price": "600000",
"rebate": 0
},
"expire": "2018/01/18"
}
}
}
2.dynamic:
{
"status": 200,
"message": "Course Details Successful",
"data": {
"id": 18,
"title": "دوره کامل و حرفه ای اکسل (50 ساعت)",
"price": {
"type": "dynamic",
"value": {
"2017-07-18 23:59:59": "165000",
"2017-08-18 23:59:59": "125000"
},
"titles": [
"دانشجویان دانشگاه تهران (داشبورد)",
"سایر علاقه مندان (داشبورد)"
],
"main_value": "165000",
"max_discount": "80"
}
}
}
3.free:
{
"status": 200,
"message": "Seminar Details Successful",
"data": {
"id": 204,
"title": "کنفرانس ملی برجام - بهمن 95",
"price": {
"type": "free",
"value": "0",
"expire": null
}
}
}
What I want is to get those three responses and serialize other values according to the type value without changing main pojo. But I have no idea how to do that.I'm using retrofit for parsing data in my app.

Related

Is there an easy way to flatten a json:api response on Android?

I'm trying to flatten the below response without having to parse it into a class. The reason for this is that the server could add or remove fields at anytime so it needs to be dynamic. We also have another service that returns lookup paths that we use to get data out of the flattened response - like "$.detail.att_one" There is a library for iOS that does the exact thing I'm looking for but as far as I can find nothing similar for Android: https://github.com/infinum/Japx
{
"data": [
{
"type": "items",
"id": "14",
"attributes": {
"item_type": "shape_circle",
"code": null,
"size": "70"
},
"relationships": {
"detail": {
"data": {
"type": "circle",
"id": "90"
}
},
"metadata": {
"data": "metadata"
}
},
"links": {
"self": "http://url/item/14"
}
}
],
"included": [
{
"type": "circle",
"id": "90",
"attributes": {
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
}
}
]}
The result I'm looking for:
{
"data": [
{
"id": "14",
"type": "items",
"item_type": "shape_circle",
"code": null,
"size": "70",
"metadata": {
"data": "metadata"
},
"detail": {
"type": "circle",
"id": "90",
"att_one": 4,
"att_two": "11111111111",
"att_three": "Bob"
},
"links": {
"self": "http://url/item/14"
}
}
]}
There is a nice JSONAPI library that does the thing, but you have to define resource classes for it.
Check out jasminb/jsonapi-converter
It recursively flattens all the included relationships and handles inheritance.

Generate JSON Schema from JSON using Java

Is there any Java package which I can use to convert a JSON string to JSON schema? I have looked up online. I found libraries in Python, Ruby and NodeJS, but not in Java
All the Java libraries generate JSON schema from a POJO
I think that you can try this library on github it does exactly what you want from a JSON, You only need to build it and use json-string-schema-generator
String json = "{\"sectors\": [{\"times\":[{\"intensity\":30," +
"\"start\":{\"hour\":8,\"minute\":30},\"end\":{\"hour\":17,\"minute\":0}}," +
"{\"intensity\":10,\"start\":{\"hour\":17,\"minute\":5},\"end\":{\"hour\":23,\"minute\":55}}]," +
"\"id\":\"dbea21eb-57b5-44c9-a953-f61816fd5876\"}]}";
String result = JsonSchemaGenerator.outputAsString("Schedule", "this is a test", json);
/* sample output
{
"title": "Schedule",
"description": "this is a test",
"type": "object",
"properties": {
"sectors": {
"type": "array",
"items": {
"properties": {
"times": {
"type": "array",
"items": {
"properties": {
"intensity": {
"type": "number"
},
"start": {
"type": "object",
"properties": {
"hour": {
"type": "number"
},
"minute": {
"type": "number"
}
}
},
"end": {
"type": "object",
"properties": {
"hour": {
"type": "number"
},
"minute": {
"type": "number"
}
}
}
}
}
},
"id": {
"type": "string"
}
}
}
}
}
}
*/
// To generate JSON schema into a file
JsonSchemaGenerator.outputAsFile("Schedule", "this is a test", json, "output-schema.json");
// To generate POJO(s)
JsonSchemaGenerator.outputAsPOJO("Schedule", "this is a test", json, "com.example", "generated-sources");
}

convert java.util.ArrayList to gson.JsonElement

Doing some request to the backend API, for receiving some array with JSON objects which I need to use in test run.
Using RestAssured+Junit5+Gradle+Allure.
Response response =
given()
.header("Content-Type", "application/json")
.body(jsonPayload)
.when()
.post(STAGINGSCHEDULE+signature)
.then()
.assertThat()
.statusCode(200)
.body("message", is("Payload valid"),
"payment_schedule", hasSize(greaterThan(0)))
.extract().response();
I would receive this:
ArrayList<JsonElement> jsonElement = response.path("payment_schedule.payment_dates");
This command will show me an array filled with json objects which I needed.
But a cound not convert this to the gson.JsonObject.
System.out.println("jsonElement.get(1): "+jsonElement.get(1));
Which methods I used to usually, when generating data by myself. Object is gsonObject, and array is gsonArray
callbackJournalObject.add("schedule", scheduleArray);
When I try to use
callbackJournalObject.add("schedule", jsonElement.get(1));
I get
java.lang.ClassCastException: java.util.ArrayList cannot be cast to com.google.gson.JsonElement
JSON Response body example:
{
"status": 0,
"message": "Payload valid",
"payment_schedule": [
{
"total": 16800.0,
"term": 3,
"payment_dates": [
{
"date": "16.10.2018",
"amount": 5600.0
},
{
"date": "16.11.2018",
"amount": 5600.0
},
{
"date": "17.12.2018",
"amount": 5600.0
}
]
},
{
"total": 16650.0,
"term": 6,
"payment_dates": [
{
"date": "16.10.2018",
"amount": 2800.0
},
{
"date": "16.11.2018",
"amount": 2800.0
},
{
"date": "17.12.2018",
"amount": 2800.0
},
{
"date": "16.01.2019",
"amount": 2800.0
},
{
"date": "18.02.2019",
"amount": 2800.0
},
{
"date": "18.03.2019",
"amount": 2650.0
}
]
}
]
}
That solution worked for me.
ArrayList<JsonElement> jsonElement = response.path("payment_schedule.payment_dates");
String jsonElementGet1 = String.valueOf(jsonElement.get(1));
scheduleArray = (JsonArray)jsonParser.parse(jsonElementGet1);
You need to remove the last comma at the end of the JSON as with it, it's not valid JSON. Once you've done that, try again and see if it works. (Used JSONBlob to verify the validity of the JSON).

how to convert JSON Data in two JSON array format on basis of type in JPA web API

{
"code": 200,
"message": "Success",
"data": [
{
"holidayId": 1,
"createdAt": 1334925720000,
"date": "2012-01-26",
"description": "Republic Day",
"holidayType": {
"holidayTypeId": 1,
"holidayType": "Normal"
}
},
{
"holidayId": 11,
"createdAt": 1334925720000,
"date": "2012-03-23",
"description": "Ugadi",
"holidayType": {
"holidayTypeId": 2,
"holidayType": "Normal"
}
},
{
"holidayId": 21,
"createdAt": 1334925720000,
"date": "2012-04-06",
"description": "Good Friday",
"holidayType": {
"holidayTypeId": 1,
"holidayType": "Normal"
}
},
{
"holidayId": 31,
"createdAt": 1334925720000,
"date": "2012-05-01",
"description": "May Day",
"holidayType": {
"holidayTypeId": 2,
"holidayType": "Normal"
}
},
}
]
}
this is my Current JSON format:
public CommonResponseModel getLeaveList() {
EntityManager entityManager = DBManager.getDBManager();
List<Holiday> result = entityManager.createQuery("FROM Holiday", Holiday.class).getResultList();
LeavesResponseWrapper model = new LeavesResponseWrapper();
model.setData(result);
DBManager.saveAndClosDB(entityManager);
return model;
}
this code i am trying to get current JSON data
But i have to get JSON Data in this format desire format:
{
"code": 200,
"message": "Holiday List",
"data": {
"normalHolidays": [
{
"name": "Diwali",
"date": "31-10-2016"
}
],
"optionalHolidays": [
{
"name": "Onam",
"date": "13-09-2016"
}
]
}
}
please help me how to achieve desire JSON format data we have two table one for holidays and another for Holidays type on the basis of that i am getting that data while i have to get To json array one for TYPE1 another for type2 i am using Jersey jar please help me how to get it .
Change the type of "data" from List<Holiday> to Map<String,List<Holiday>>.
Then based on holidayType you can separate data in setData().
Map<String,List<Holiday>> data;
setData(List<Holiday> holidays) {
List<Holiday> normalHolidays = new ArrayList<Holiday>();
List<Holiday> optionalHolidays = new ArrayList<Holiday>();
for(Holiday holiday : holidays) {
if("Normal".equals(holiday.holidayType.holidayType)) {
normalHolidays.add(holiday);
} else {
optionalHolidays.add(holiday);
}
}
data = new HashMap<String,List<Holiday>>();
data.put("normalHolidays", normalHolidays);
data.put("optionalHolidays", optionalHolidays);
}

Issue with json Content type for DeepInsert

I'm trying deepinsert with Json on the service,http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/OData/OData.svc/Categories with body--
{
"d" : {
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Categories(0)", "type": "ODataDemo.Category"
}, "ID": 97, "Name": "Food", "Products": [
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products( 0)", "type": "ODataDemo.Product"
}, "ID": 97, "Name": "Bread", "Description": "Whole grain bread", "ReleaseDate": "\/Date(694224000000)\/", "DiscontinuedDate": null, "Rating": 4, "Price": "2.5", "Category": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Category"
}
}, "Supplier": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Supplier"
}
}
}
]
}
}
and I get the 400 Bad request with error description:
{
error: {
code: ""
message: {
lang: "en-US"
value: "Error processing request stream. The property name 'd' specified for type 'ODataDemo.Category' is not valid."
}-
}-
}
Can someone help me figure out what I'm doing wrong here?
There is no need to append "d" in the body of post request.
Remove the "d" and send the body like this:
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Categories(0)", "type": "ODataDemo.Category"
}, "ID": 97, "Name": "Food", "Products": [
{
"__metadata": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products( 0)", "type": "ODataDemo.Product"
}, "ID": 97, "Name": "Bread", "Description": "Whole grain bread", "ReleaseDate": "\/Date(694224000000)\/", "DiscontinuedDate": null, "Rating": 4, "Price": "2.5", "Category": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Category"
}
}, "Supplier": {
"__deferred": {
"uri":"http://services.odata.org/(S(egpbfjhhvili4slwaq1p2lvt))/V2/odata/OData.svc/Products(0)/Supplier"
}
}
}
]
}

Categories

Resources