OffsetDateTime object should not be converted to json object [duplicate] - java

This question already has answers here:
Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps in spring
(5 answers)
Closed 1 year ago.
I am converting java object into json object. But OffsetDatetime also being converted to json format. Is it possible to keep the time object as OffsetDatetime timestamp itself.
Java object
{
"start_date": "2022-01-01T13:45:00+01:00",
"origin": {
"type": "AIRPORT",
"search_display_name": "Malmo, Sweden (MMX-Sturup)",
"search_string": "MMX",
"city": "Malmo"
}
}
After converting to json, getting as follows
{
"start_date": {
"offset": {
"total_seconds": 0,
"id": "Z",
"rules": {
"fixed_offset": true,
"transition_rules": [
],
"transitions": [
]
}
},
"day_of_month": 1,
"day_of_week": "SATURDAY",
"day_of_year": 1,
"month": "JANUARY",
"month_value": 1,
"year": 2022,
"hour": 12,
"minute": 45,
"nano": 0,
"second": 0
},
"origin": {
"search_display_name": "Malmo, Sweden (MMX-Sturup)",
"search_string": "MMX",
"city": "Malmo"
}
}
Is it possible to keep offsetDateTime like this "2022-01-01T13:45:00+01:00"
Java object will be converted to json using this method objectMapper.valueToTree(response)
Object mapper configuration as follows
#Bean("objectMapperJavaTime")
public ObjectMapper objectMapperJavaTime() {
return JacksonObjectMapperFactory.createMapperWithDefaultConfigurations()
.registerModule(new JavaTimeModule())
.enable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
}
public class JacksonObjectMapperFactory {
public static ObjectMapper createMapperWithDefaultConfigurations(){
return new Jackson2ObjectMapperBuilder()
.featuresToDisable(WRITE_DATES_AS_TIMESTAMPS)
.failOnUnknownProperties(false)
.serializationInclusion(NON_NULL)
.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.modules(new JodaModule())
.build();
}
}

Often there are issues attempting to disable the WRITE_DATES_AS_TIMESTAMPS feature on creation like that.
So the solution is not to apply the featrue on creation, so remove this:
.featuresToDisable(WRITE_DATES_AS_TIMESTAMPS)....
And instead of setting feature and returning the objectMapper on one line, you can break it up and set the feature to false after the ObjectMapper has been created:
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);`
Then return the objectMapper.

Related

Why does Quarkus #Produces(MediaType.APPLICATION_JSON) automatically add the array wrapper and comma to values?

I have a POST Rest API developed using Quarkus with #Produces(MediaType.APPLICATION_JSON) this method returns the list of customers asynchronously. But the problem is that it adds the additional array wrapper and comma separation, which is not required. Everything works fine when used with MediaType.TEXT_PLAIN but since my response is of JSON type I want to keep MediaType.APPLICATION_JSON. Is there anyway to avoid the modification to response?
For example following is the response I am getting with #Produces(MediaType.APPLICATION_JSON). You can see it adds unwanted commas and arrays within my response:
[
{
"isA": "customerDocument",
"createdOn": "2022-10-10T12:29:43",
"customerBody": {
"customerList": [,
{
"name": "Batman",
"age": 45,
"city": "gotham"
},
{
"name": "superman",
"age": 50,
"city": "moon"
},
]
}
}]
The response I would like is correctly achievable with MediaType.TEXT_PLAIN:
{
"isA": "customerDocument",
"createdOn": "2022-10-10T12:29:43",
"customerBody": {
"customerList": [
{
"name": "Batman",
"age": 45,
"city": "gotham"
},
{
"name": "superman",
"age": 50,
"city": "moon"
}
]
}
}
When I use text/plain, everything works fine. Is there something that I can modify to avoid the addition of array wrapper and comma when using with application/json?
I believe this is happening because I am generating the elements in customerList asynchronously using the SmallRye Mutin Multi<String>. Can someone please provide some suggestion?
The following is the Quarkus Rest API for GET requests:
#Path("/testData")
#GET
#Produces(MediaType.APPLICATION_JSON)
public Multi <String> test() throws IOException {
return Multi.createFrom().items(IOUtils.toString(getClass().getResourceAsStream("/TestJSON.json"), StandardCharsets.UTF_8));
}

Delete object from array in MongoDB in Java

[{
"_id": {
"$oid": "5ee227d69dba6729ca8938fc"
},
"uuid": "4e9be217-a2c7-490f-86b7-2d46a69980a3",
"locks": {
"furnace_1591879638": {
"type": "FURNACE",
"location": {
"world": "world",
"x": -33,
"y": 73,
"z": -227
},
"created": "Thu Jun 11 14:47:18 CEST 2020",
"peopleWithAccess": []
},
"chest_1591903237541": {
"type": "CHEST",
"location": {
"world": "world",
"x": -36,
"y": 73,
"z": -224
},
"created": "Thu Jun 11 21:20:37 CEST 2020",
"peopleWithAccess": []
}
}
},{
"_id": {
"$oid": "5ee2864622c67536a249fb0a"
},
"uuid": "6fc93f76-b03b-4af3-a679-ac53cafdb288",
"locks": {}
}]
Hi,
I just stared with MongoDB and I was used to working with MySQL so this is really confusing for me. I've been trying to delete a object from an array but unsuccessfully. I tried this:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", "locks." + id))
That gave me an error Modifiers operate on fields but we found type string instead.
How would I delete for exmaple object furnace_1591879638 from player with uuid 4e9be217-a2c7-490f-86b7-2d46a69980a3 in Java?
Unfortunately, we cannot use the $unset operator to remove objects from an array, since the operator can only remove whole fields. For removing and inserting in an array, we are using $pull and $push.
I would recommend you to look up, both Bson Updates and Filters class because they are making it way easier, instead of using the operators (At least for the mongodb driver version 3.8 or higher; I do not know if older versions support Bson).
With the help of these classes, you could extend your
MongoManager
class and try something like this:
public void pullByFilter(String queryField, Object queryValue, String arrayName, Object value) {
MongoCollection<Document> collection = getCollection("players");
Bson update = Updates.pullByFilter(Filters.eq(arrayName, value));
collection.updateOne(Filters.eq(queryField, queryValue), update);
}
This method should remove the specified value from the array.
Just for clearance: the queryField and queryValue parameters are used to identify the document (for you, the queryField should be "uuid" and the queryValue should be the players UUID as string).
Lastly, I think the method you tried with the $unset operator is giving you an error because you need to specify a new Document after the operator.
This:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", "locks." + id))
should rather be:
getMongoManager().getDatabase().getCollection("players").updateOne(new Document("uuid", player.getUniqueId().toString()),
new Document("$unset", new Document("locks", id)))
Also, a good tutorial for updating documents can be found here.

How to parse JSON nested arrays [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
"sport_events": [
{
"id": "sr:match:12606716",
"scheduled": "2017-09-27T10:00:00+00:00",
"start_time_tbd": false,
"status": "closed",
"tournament_round": {
"type": "group",
"number": 1,
"group": "Gr. 4"
},
"season": {
"id": "sr:season:45960",
"name": "U17 European Ch.ship QF 17/18",
"start_date": "2017-09-27",
"end_date": "2018-04-30",
"year": "17/18",
"tournament_id": "sr:tournament:755"
},
"tournament": {
"id": "sr:tournament:755",
"name": "U17 European Ch.ship QF",
"sport": {
"id": "sr:sport:1",
"name": "Soccer"
},
"category": {
"id": "sr:category:392",
"name": "International Youth"
}
},
"competitors": [
{
"id": "sr:competitor:22646",
"name": "Russia",
"country": "Russia",
"country_code": "RUS",
"abbreviation": "RUS",
"qualifier": "home"
},
{
"id": "sr:competitor:22601",
"name": "Faroe Islands",
"country": "Faroe Islands",
"country_code": "FRO",
"abbreviation": "FRO",
"qualifier": "away"
}
]
},
Add gson to your project by adding this into your build-script.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Now create the classes you need but first correct your json string. I guess you forgot a attributename at the beginning. This is your new best friend: json formatter online
After you corrected your json-string and you´ve created your Wrapper and Pojo model-classes with the needed attributes, you parse the string back into the wrapper-object and with getter/setter you get change/get data out of it.
Gson gson = new GsonBuilder().create();
Wrapper wrap = gson.fromJson(jsonString, Wrapper.class);
Don´t forget try-catch block because there can be many thrown exceptions.
Good luck to you.
How-to-for-beginner

parse json object from json array in java using com.fasterxml.jackson.databind.JsonNode;

I am trying to parse some json which is a groupd of objects within an array. I am not fluent with java and having a hard time figuring out how to do this.
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
JsonNode messageNode = mapper.readTree(post);
if (!messageNode.isArray()){
try {
throw new Exception("INVALID JSON");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<String> listObjects = null;
JsonParser parser = mapper.getFactory().createParser(post);
the json format:
{
"data": [
{
"id": "897569693587466_897626706915098",
"from": {
"id": "1809583315",
"name": "Lena Cann Jordan"
},
"message": "Amen.",
"can_remove": false,
"created_time": "2014-11-11T22:41:11+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897627376915031",
"from": {
"id": "1776031725",
"name": "Kyla Munford"
},
"message": "Tell me what my God can't do!!!",
"can_remove": false,
"created_time": "2014-11-11T22:42:51+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897631636914605",
"from": {
"id": "100000106496788",
"name": "Sarah Barklow Tyson"
},
"message": "That's bc God is awesome!! He can give or take away!! \ud83d\ude4f\u2795",
"can_remove": false,
"created_time": "2014-11-11T22:49:46+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpVMk1USXdNalExTkRrd09qRTBNVFUzTkRrNU5qTTZOREE9",
"before": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpJMk56QTJPVEUxTURrNE9qRTBNVFUzTkRVMk56RTZNelU9"
},
"previous": "some link"
}
}
This is the json from the facebook graph api. I also need to extract the cursors and links below so would they also appear as one of the objects.
Appreciate advice.
Thanks
I think the real question is what you are trying to achieve? You are already parsing JSON into a tree model (JsonNode), and from that point on you can traverse content freely, using methods get, path and at (which uses JSON Pointer expression).
Or, as suggested by Samwise above, could consider modeling Java classes with same structure as JSON, so that you would have even easier time accessing data as regular Java objects. If so, you'd parse it simply by:
Graph graph = mapper.readValue(post);
Data d = graph.getData().get(0); // for first entry in "data" List

Convert json response to java object

I have json response and I generated java code from this json by tools .But this json object have key like #size ,#order etc ... ,So in my java code some invalid identifier has been generated. When I removed this # symbol with java code I am able to catch the response of json value in my java object expect these value.
I am sure some json annotation is available to do this , means if the json key is not matching with java Object then we can map through this json annotation.
I tried with some Json annotation but is not worked for me and I confused which annotation should I used with getter methods .
here my json code below :-
{
"HotelListResponse": {
"cachedSupplierResponse": {
"#cachedTime": "0",
"#candidatePreptime": "111",
"#matchedCurrency": "true",
"#matchedLocale": "true",
"#otherOverheadTime": "4",
"#supplierRequestNum": "211",
"#supplierResponseNum": "20",
"#supplierResponseTime": "405",
"#tpidUsed": "5001"
},
"cacheKey": "302c317:13443ffb599:-7712",
"cacheLocation": "10.186.168.61:7302",
"customerSessionId": "0ABAA83D-2C31-7913-4432-FFB599907714",
"HotelList": {
"#activePropertyCount": "237",
"#size": "1",
"HotelSummary": {
"#ubsScore": "1867",
"#order": "0",
"hotelId": 127092,
"name": "The Edgewater - A Noble House Hotel",
"address1": "Pier 67, 2411 Alaskan Way",
"city": "Seattle",
"stateProvinceCode": "WA",
"postalCode": 98121,
"countryCode": "US",
"airportCode": "SEA",
"supplierType": "E",
"propertyCategory": 1,
"hotelRating": 4,
"confidenceRating": 85,
"amenityMask": 6259019,
"tripAdvisorRating": 4,
"tripAdvisorReviewCount": 590,
"tripAdvisorRatingUrl": "http://www.tripadvisor.com/img/cdsi/img2/ratings/traveler/4.0-12345-4.gif",
"locationDescription": "Near Washington State Convention & Trade Center",
"shortDescription": "<p><b>Location. </b> <br />The Edgewater - A Noble House Hotel is a business-friendly hotel located in central Seattle, close to Odyssey - The Maritime Discovery Center, Washington State Convention &",
"highRate": 249,
"lowRate": 186.75,
"rateCurrencyCode": "USD",
"latitude": 47.61252,
"longitude": -122.35013,
"proximityDistance": 11.898841,
"proximityUnit": "MI",
"hotelInDestination": true,
"thumbNailUrl": "/hotels/1000000/20000/11200/11133/11133_73_t.jpg",
"deepLink": "http://travel.ian.com/index.jsp?pageName=hotAvail&cid=55505&hotelID=127092&mode=2&numberOfRooms=2&room-0-adult-total=1&room-0-child-total=1&room-0-child-0-age=3&room-1-adult-total=1&room-1-child-total=1&room-1-child-0-age=5&arrivalMonth=8&arrivalDay=4&departureMonth=8&departureDay=5&showInfo=true&locale=en_US&currencyCode=USD",
"RoomRateDetailsList": {
"RoomRateDetails": {
"roomTypeCode": 1160,
"rateCode": 1221260,
"maxRoomOccupancy": 2,
"quotedRoomOccupancy": 2,
"minGuestAge": 0,
"roomDescription": "City Lodge - Nonrefundable",
"promoId": 200803780,
"promoDescription": "7-Day Advance Purchase Special (Nonrefundable)",
"currentAllotment": 10,
"propertyAvailable": true,
"propertyRestricted": false,
"expediaPropertyId": 11133,
"rateKey": "f3525aff-9f4d-4d92-bc1c-144628fcaa30",
"nonRefundable": true,
"RateInfos": {
"#size": "1",
"RateInfo": {
"#rateChange": "false",
"#promo": "true",
"#priceBreakdown": "true",
"RoomGroup": {
"Room": [
{
"numberOfAdults": 1,
"numberOfChildren": 1,
"childAges": 3
},
{
"numberOfAdults": 1,
"numberOfChildren": 1,
"childAges": 5
}
]
},
"ChargeableRateInfo": {
"#commissionableUsdTotal": "373.5",
"#total": "441.74",
"#surchargeTotal": "68.24",
"#nightlyRateTotal": "373.5",
"#averageBaseRate": "249.0",
"#averageRate": "186.75",
"#maxNightlyRate": "186.75",
"#currencyCode": "USD",
"NightlyRatesPerRoom": {
"#size": "1",
"NightlyRate": {
"#promo": "true",
"#rate": "186.75",
"#baseRate": "249.0"
}
},
"Surcharges": {
"#size": "1",
"Surcharge": {
"#amount": "68.24",
"#type": "TaxAndServiceFee"
}
}
}
}
}
}
}
}
}
}
}
and I generated the java classes from above mention json by this tool: http://jsongen.byingtondesign.com/
So here how to map[ #key (value of key start with #) ] in our java classes. Initially java class have #identifier_name but java compiler not support variable name start with # so I have to remove it.And then I am not able to map json value to this variable.
Any help would be appreciated.
Thanks in Advance

Categories

Resources