Change the Date Default Format in Jettison - jackson

Can the Default Date format returned by Jettison Library can be changed ?
This is the default Date format
{
"post": {
"activityDate": "2012-07-03T16:15:29.111-04:00",
"modfiedDate": "2012-07-03T16:15:29.111-04:00",
"createdDate": "2012-07-03T16:15:29.111-04:00"
}
}
can that be changed ?
We can do this in Jakson using org.codehaus.jackson.map.JsonSerialize annotation.
How to do this in Jettison ?
Is there any similar class in Jettison ?
Thanks

This is can be done using XMLAdapters
public class DateAdapter extends XmlAdapter {
/**
* This method is called when we return the DTO Date property to UI, We
* convert the date to UI date format
*/
#Override
public String marshal(Date inputDate) throws Exception {
.........
return dateStr;
}
/**
* This method is called when UI sends date String and we set the DTO Date
* property
*/
#Override
public Date unmarshal(String inputDateStr) throws Exception {
................
return inputdate;
}
}

Related

EasyAdmin 3 Object of class DateTime could not be converted to string

I'm having a problem with easy admin 3.
I followed the instructions of the symfony doc but I end up with this error: Object of class DateTime could not be converted to string when rendering the admin.
Thank you for you help !
class ArticleCrudController extends AbstractCrudController
{
/**
* #return string
*/
public static function getEntityFqcn(): string
{
return Article::class;
}
/**
* #param Crud $crud
* #return Crud
*/
public function configureCrud(Crud $crud): Crud
{
return $crud
->setDateFormat('d/m/Y')
// ...
;
}
}
In your "Article" entity you have a DateTime property. You need to implement method
configureFields and return an DateTimeField. I don't know if it's the good way but it will fix your error.

Converting String to Date when using functional WebFlux

When we send a URL with request parameters that needs to be converted to date, in SpringMVC we can do something like the code below in the controller and the fasterxml json library does the automatic conversion!
public String getFare(##RequestParam(value = "flightDate") #DateTimeFormat(iso = ISO.DATE) LocalDate date)
But how to achieve the same when we use the HandlerFunction (Spring webflux)? For example, in my HandlerFunction
public HandlerFunction<ServerResponse> getFare = serverRequest ->
{
Optional<String> flightDate = serverRequest.queryParam("flightDate");
}
The code serverRequest.queryParam("flightDate") gives a String. Is it possible to get the same automatic conversion here?
No. (you can look at Spring's source code and see that no other way to get the queryParams other than getting it as Optional<String>)
You must convert the field to Date yourself
Date flightDate = request.queryParam("flightDate ")
.map(date -> {
try {
return new SimpleDateFormat("dd-MMM-yyyy").parse(date);
} catch (ParseException e) {
return null;
}
}).orElse(null);

Laravel Carbon error data missing with casting

I have a date property, and I try to cast it to the DateTime format during saving.
protected $casts = [
'date' => 'datetime:Y-m-d H:m',
];
In my controller, I have the following method.
public function change(int $gameSerieId, Request $request)
{
try {
$gameSerie = GameSerie::findOrFail($gameSerieId);
$gameSerie->update($request->all());
return response()->json('ok');
} catch (\Exception $exception) {
throw new GameApiException('Something went wrong!');
}
}
However, I get an error "Data Missing" because my date input format looks like a string: 2019-11-17 21:00.
I have found the ability of use mutators for set attributes
public function setDateAttribute($date)
{
$this->attributes['date'] = Carbon::make($date);
}
https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator

Cast route parameter in Nancy is always null

I have a Nancy module which uses a function which expects as parameters a string (a captured pattern from a route) and a method group. When trying to pass the parameter directly it will not compile as I "cannot use a method group as an argument to a dynamically dispatched operation".
I have created a second route which attempts to cast the dynamic to a string, but this always returns null.
using System;
using Nancy;
public class MyModule : NancyModule
{
public MyModule()
{
//Get["/path/{Name}/action"] = parameters =>
// {
// return MyMethod(parameters.Name, methodToBeCalled); // this does not compile
// };
Get["/path/{Name}/anotherAction"] = parameters =>
{
return MyMethod(parameters.Name as string, anotherMethodToBeCalled);
};
}
public Response MyMethod(string name, Func<int> doSomething)
{
doSomething();
return Response.AsText(string.Format("Hello {0}", name));
}
public int methodToBeCalled()
{
return -1;
}
public int anotherMethodToBeCalled()
{
return 1;
}
}
Tested with the following class in a separate project:
using System;
using Nancy;
using Nancy.Testing;
using NUnit.Framework;
[TestFixture]
public class MyModuleTest
{
Browser browser;
[SetUp]
public void SetUp()
{
browser = new Browser(with =>
{
with.Module<MyModule>();
with.EnableAutoRegistration();
});
}
[Test]
public void Can_Get_View()
{
// When
var result = browser.Get("/path/foobar/anotherAction", with => with.HttpRequest());
// Then
Assert.AreEqual(HttpStatusCode.OK, result.StatusCode);
Assert.AreEqual("Hello foobar", result.Body.AsString()); //fails as parameters.Name is always null when cast to a string
}
}
You can find the whole test over on github
I've had similar issues when using 'as' so I tend to use explicitly cast it:
return MyMethod((string)parameters.Name, anotherMethodToBeCalled);
Also I think there was a bug raised with the casing on parameters, but I think it's better to keep them lowercase:
Get["/path/{name}/anotherAction"]
(string)parameters.name
Your code works for me with upper case and lowercase, using the explicit cast.

Jackson : Conditional select the fields

I have a scenario where i need to use the payload as
{"authType":"PDS"}
or
{"authType":"xyz","authType2":"abc",}
or
{"authType":"xyz","authType2":"abc","authType3":"123"}
or
any combination except for null values.
referring to the code i have 3 fields but only not null value fields be used.
Basically i don't want to include the field which has null value.
Are there any annotations to be used to get it done
public class AuthJSONRequest {
private String authType;
private String authType2;
private String authType3;
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getAuthType2() {
return authType2;
}
public void setAuthType2(String authType2) {
this.authType2 = authType2;
}
public String getAuthType3() {
return authType3;
}
public void setAuthType3(String authType3) {
this.authType3 = authType3;
}
}
Try JSON Views? See this or this. Or for more filtering features, see this blog entry (Json Filters for example).
This is exactly what the annotation #JsonInclude in Jackson2 and #JsonSerialize in Jackson are meant for.
If you want a property to show up only when it is not equal to null, add #JsonInclude(Include.NON_NULL) resp. #JsonSerialize(include=Include.NON_NULL).