Deserialize(convert) a JsonObject to DateTime without POJO - java

I have the following jsonObject:
"dateCreated": {
"year": 2021,
"dayOfYear": 145,
"equalNow": false,
"weekyear": 2021,
"chronology": {
"zone": {
"ID": "UTC"
}
},
"weekOfWeekyear": 21,
"secondOfMinute": 10,
"millisOfDay": 10990000,
"monthOfYear": 5,
"dayOfWeek": 2,
"beforeNow": true,
"minuteOfDay": 183,
"dayOfMonth": 25,
"era": 1,
"zone": {
"ID": "UTC"
},
"yearOfCentury": 21,
"centuryOfEra": 20,
"hourOfDay": 3,
"secondOfDay": 10990,
"millis": 1621911790000,
"yearOfEra": 2021,
"minuteOfHour": 3,
"millisOfSecond": 0,
"afterNow": false
}
I need to convert it for this format:
2021-05-25T03:03:10.000Z
Since I don't have a pojo for that object, it's coming from a jsonArray, I'm struggling to get a Datetime from it.
I tried ObjectMapper, JSON(GSON) and still no success.
Does anyone have a clue how can I do it?
edit.: It's a list of Recordings that I converted to JsonArray (to manipulate, adding another field into the json). When I convert the list to jsonArray, that field (type DateTime) becomes serialized and I need it back to the correct format to pass it forward.
Recording.class;
private final DateTime dateCreated;
List<Recording> listRecordings;
JSONArray jsonArray = new JSONArray(listRecordings);
jsonArray ->
[
{
"offset": 179161383840,
"type": "AUDIO",
"duration": 232,
"codec": "OPUS",
"dateCreated": {
"year": 2021,
"dayOfYear": 145,
"equalNow": false,
"weekyear": 2021,
"chronology": {
"zone": {
"ID": "UTC"
}
},
"weekOfWeekyear": 21,
"secondOfMinute": 10,
"millisOfDay": 10990000,
"monthOfYear": 5,
"dayOfWeek": 2,
"beforeNow": true,
"minuteOfDay": 183,
"dayOfMonth": 25,
"era": 1,
"zone": {
"ID": "UTC"
},
"yearOfCentury": 21,
"centuryOfEra": 20,
"hourOfDay": 3,
"secondOfDay": 10990,
"millis": 1621911790000,
"yearOfEra": 2021,
"minuteOfHour": 3,
"millisOfSecond": 0,
"afterNow": false
},
"size": 521517,
"containerFormat": "MKA",
"status": "COMPLETED"
}
]
I need to revert back dateCreated for the original format: 2021-05-25T03:03:10.000Z
Edit3.:
My workaround:
for (Recording recording : listRecordings) {
Object jsonObject = JSONObject.wrap(recording);
((JSONObject) jsonObject).put("dateCreated", recording.getDateCreated());
jsonArray.put(jsonObject);
}
Best Regards,

Related

Spring boot - Joda DateTime serialisation

In an Spring boot app, I have a DTO class with a org.joda.time.DateTime field type.
This DTO is the web response body in an endpoint and Spring boot is serialisating it to a timestamp.
I don't want that behaviors. Instead of that, I want DateTime to be serialised as a POJO.
This is an example:
Actual response:
{
"thisDate": 1566518936800
}
Expected response:
{
"thisDate": {
"monthOfYear": 8,
"centuryOfEra": 20,
"yearOfEra": 2019,
"yearOfCentury": 19,
"weekyear": 2019,
"weekOfWeekyear": 34,
"hourOfDay": 17,
"minuteOfHour": 8,
"secondOfMinute": 56,
"millisOfSecond": 800,
"secondOfDay": 61736,
"millisOfDay": 61736800,
"minuteOfDay": 1028,
"era": 1,
"dayOfMonth": 22,
"dayOfWeek": 4,
"dayOfYear": 234,
"year": 2019,
"chronology": {
"zone": {
"fixed": false,
"uncachedZone": {
"cachable": true,
"fixed": false,
"id": "America/Los_Angeles"
},
"id": "America/Los_Angeles"
}
},
"millis": 1566518936800,
"zone": {
"fixed": false,
"uncachedZone": {
"cachable": true,
"fixed": false,
"id": "America/Los_Angeles"
},
"id": "America/Los_Angeles"
},
"afterNow": false,
"beforeNow": true,
"equalNow": false
}
}
I know this is not the most common case but is what I need; actually the most common case is exactly the opposite.
Thanks in advance

Convert the flat Java Object that was created from the DB read, into nested Json object

The threaded comments are stored in Database as flat records with commenId and ParentCommentId. Like below.
commentId : 1
userId    : 815
userFName:Joe
userLName:Doe
timeStamp:12345678888
commentText:""
parentCommentId:0
commentId : 2
userId    : 615
userFirstName:Ken
userLastName:Tait
timeStamp:12345678988
commentText:"Comment text"
parentCommentId:1
commentId : 3
userId    : 415
userFirstName:Brain
userLastName:Dell
timeStamp:12345678
commentText:"Comment text"
parentCommentId:0
I build the Java object using the following Java class
public class Comment {
int commentId;
int userId;
String userFName;
String userLName;
long timeStamp;
String commentText;
int parCommId;
}
List<Comment> comments;
I have the List of comments object. Now I have to traverse the list and convert this list of comment object into nested Json object. The comment objects with parCommId == 0 are the top level comment and the other comment objects (parCommId != 0) should be nested under the commentId of the comment object.
In the above example, the output should be nested like below
CommentId_1
CommentId_2
CommentID_3
As suggested in the comments, let's add a List<Comment> field in Comment.class.
Then, assuming the input from the DB is:
List<Comment> comments = Arrays.asList(
new Comment(1, 6, "John", "Snow", 0, "asd", 0),
new Comment(2, 6, "Tif", "Snow", 0, "asd2", 1),
new Comment(3, 6, "Yur", "Snow", 0, "asd", 2),
new Comment(4, 6, "Mrr", "Snow", 0, "asd", 0),
new Comment(5, 6, "Mrr", "Snow", 0, "asd", 2)
);
You can do the following:
Map<Integer, List<Comment>> parentToComments = comments.stream()
.collect(Collectors.groupingBy(Comment::getParCommId));
comments.forEach(comment -> {
List<Comment> children = parentToComments.get(comment.getCommentId());
comment.setChildren(children);
});
ObjectMapper objectMapper = new ObjectMapper();
String commentsJson = objectMapper.writeValueAsString(parentToComments.get(0));
Output:
[{
"commentId": 1,
"userId": 6,
"userFName": "John",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": [{
"commentId": 2,
"userId": 6,
"userFName": "Tif",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd2",
"parCommId": 1,
"children": [{
"commentId": 3,
"userId": 6,
"userFName": "Yur",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}, {
"commentId": 5,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 2,
"children": null
}]
}]
}, {
"commentId": 4,
"userId": 6,
"userFName": "Mrr",
"userLName": "Snow",
"timeStamp": 0,
"commentText": "asd",
"parCommId": 0,
"children": null
}]

Is it possible to turn an array of objects into a map during deserialisation using Gson?

Using the Steam API found here api.steampowered.com/IEconItems_440/GetPlayerItems/v0001/ I get a JSON string like the one below. As you can see, it contains an array of item objects. What I'd like to do is to turn this array into a Map where the defindex is the key and the value is the corresponding item object at point of deserialisation using GSON.
Is this possible or do I have to do that after it's created the objects and populated the array?
"result": {
"status": 1,
"num_backpack_slots": 800,
"items": [
{
"id": 12222222,
"original_id": 333333333,
"defindex": 45,
"level": 10,
"quality": 3,
"inventory": 2147483922,
"quantity": 1,
"origin": 0,
"style": 0,
"attributes": [
{
//...
]
},
{
"id": 3332222222,
"original_id": 554545465,
"defindex": 116,
"level": 10,
"quality": 6,
"inventory": 2147483865,
"quantity": 1,
"origin": 0,
"equipped": [
{
"class": 6,
"slot": 7
},
{
"class": 8,
"slot": 7
}
]
,
"style": 1,
"attributes": [
//...
]
},
{
"id": 4658518468,
"original_id": 897545164648,
"defindex": 130,
"level": 5,
"quality": 3,
"inventory": 2147484134,
"quantity": 1,
"origin": 0,
"attributes": [
{
//...
]
}
]

GSON cannot parse Zomato restaurant collection

I am using Java and Akka to design new app at home, but I am facing problems pasing api response from Zomato.
The JSON response can be found below. I've created Class Restaurant with List of objects Restaurant. How should I parse it?
{
"results_found": 131,
"results_start": 0,
"results_shown": 10,
"restaurants": [
{
"restaurant": {
"R": {
"res_id": 6103211
},
"apikey": "4972ea7a10293fc07e997364eef03d3d",
"id": "6103211",
"name": "Dishoom",
"url": "https://www.zomato.com/london/dishoom-covent-garden?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "12 Upper St Martin's Lane, Covent Garden, London WC2H 9FB",
"locality": "Upper St Martin's Lane, Covent Garden",
"city": "London",
"city_id": 61,
"latitude": "51.5124170000",
"longitude": "-0.1271640000",
"zipcode": "WC2H 9FB",
"country_id": 215,
"locality_verbose": "Upper St Martin's Lane, Covent Garden, London"
},
"switch_to_order_menu": 0,
"cuisines": "Indian, North Indian, Curry, Cafe",
"average_cost_for_two": 35,
"price_range": 2,
"currency": "\u00a3",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.9",
"rating_text": "Excellent",
"rating_color": "3F7E00",
"votes": "919"
},
"photos_url": "https://www.zomato.com/london/dishoom-covent-garden/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/london/dishoom-covent-garden/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"include_bogo_offers": true,
"deeplink": "zomato://restaurant/6103211",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/london/dishoom-covent-garden/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
If the json is exactly the same of what you've pasted here, it seems that it's not a valid json. Try with this one:
{
"results_found": 131,
"results_start": 0,
"results_shown": 10,
"restaurants": [{
"restaurant": {
"R": {
"res_id": 6103211
},
"apikey": "4972ea7a10293fc07e997364eef03d3d",
"id": "6103211",
"name": "Dishoom",
"url": "https://www.zomato.com/london/dishoom-covent-garden?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "12 Upper St Martin's Lane, Covent Garden, London WC2H 9FB",
"locality": "Upper St Martin's Lane, Covent Garden",
"city": "London",
"city_id": 61,
"latitude": "51.5124170000",
"longitude": "-0.1271640000",
"zipcode": "WC2H 9FB",
"country_id": 215,
"locality_verbose": "Upper St Martin's Lane, Covent Garden, London"
},
"switch_to_order_menu": 0,
"cuisines": "Indian, North Indian, Curry, Cafe",
"average_cost_for_two": 35,
"price_range": 2,
"currency": "\u00a3",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"user_rating": {
"aggregate_rating": "4.9",
"rating_text": "Excellent",
"rating_color": "3F7E00",
"votes": "919"
},
"photos_url": "https://www.zomato.com/london/dishoom-covent-garden/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/london/dishoom-covent-garden/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/res_imagery/6103211_RESTAURANT_19f7b41684765da1a700c2818f16cde0.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"include_bogo_offers": true,
"deeplink": "zomato://restaurant/6103211",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/london/dishoom-covent-garden/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
}]
}
The first thing is the JSON is invalid. I assume you can manage a valid JSON. After validating the JSON.
Create a Restaurant POJO class first.
The properties for Restaurant class:
R: obj
apikey: string
location: obj
.... like .....
add all the fields that you need.
After that, Use code to parse. but first, fetch out the restaurants array from the JSON.
gson.fromJson(restaurants, Restaurant[].class);

JSON Object changes randomly from api

I get data from an API in which the JSON object changes randomly, like if it is at "position": 1, now it will change randomly to "number": 1. So, how can I check in my application if the object is at "position": 1 or "number": 1 and use it as int?
JSON :-
{
"now": [{
"time": {
"starts_in": 0,
"ends_in": 79580,
"starts_at": 0,
"ends_at": "2018-01-21T08:00:00.788Z"
},
"coins": {
"free": 8,
"first_win": 16,
"max": 52,
"collected": 0
},
"unk1": -88317689,
"position": 1,
"xp_multiplier": 0,
"location_scid": {
"scid_type": 15,
"scid_id": 1
},
"tid": "TID_WANTED_3",
"location": "Terre",
"mode": {
"name": "Bty",
"color": "#0884FA",
"description": " The team wins!"
},
"unk4": 0,
"info": "",
"unk5": 0,
"unk6": 0
}, {
"time": {
"starts_in": 0,
"ends_in": 36380,
"starts_at": 0,
"ends_at": "2018-01-20T20:00:00.788Z"
},
"coins": {
"free": 24,
"first_win": 0,
"max": 32,
"collected": 0
}
}],
"later": [{
"time": {
"starts_in": 79580,
"ends_in": 165980,
"starts_at": "2018-01-21T08:00:00.788Z",
"ends_at": "2018-01-22T08:00:00.788Z"
},
"coins": {
"free": 8,
"first_win": 16,
"max": 52,
"collected": 0
},
"unk1": -88217689,
"position": 1,
"xp_multiplier": 0,
"location_scid": {
"scid_type": 15,
"scid_id": 7
},
"tid": "TID_GOLDRUSH_1",
"location": "Mine",
"mode": {
"name": "Grab",
"color": "#AA57CF",
"description": " An. "
}
}]
}
Thanks in advance :)
JSONObject c = //Your jsonObject;
String position = c.getInt("position");
String number = c.getInt("number");
if(position!=null){
//TODO You know it is position and it's int value
}else if(number!=null){
//TODO You know it is number and it's int value
}else{
//TODO Its neither of two
}
If you're using Gson to convert your JSON to a class, you can use both position and number as attributes for your destination class.
After that, check which one is null and which one is not and use that is not null as your number.
Just try this one,
JSONObject object = (Your jsonObject);
if(object.has("position")){
** do your code here **
}else if(object.has("number"){
** do your code here **
}

Categories

Resources