Haven't found anything out there after doing some searches.
I'm wondering if
there's any way to specify how an asmx WebService serializes a DateTime to json?
Can this be setup as a webconfig setting? Or am I stuck with the /Date(millis)/ format?
I don't know any way to do this, but one solution is to use a double value (or possibly long if you're not interested in fractional milliseconds) which contains the total number of milliseconds since the UnixEpoch. You could use a helper class something like:
public static class DateTimeExtensions
{
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1);
public static double ToUnixTime(this DateTime dateTime)
{
return (dateTime - UnixEpoch).TotalMilliseconds;
}
...
}
Related
I have a field in my Car POJO class that looks like this:
#DynamoDBAttribute(attributeName = "release_year")
private int year;
I want to add a Car to my database by sending a POST request via Postman. I was hoping that my JSON body could look like this:
{
"release_year": 2015
}
It is not possible, I have to use 'year' instead. In my dynamoDB, the field is called 'release_year';
My question is: is it possible to use 'release_year' in my POST request somehow, but still keep 'year' in the POJO class? Or do I have to rename the field to 'release_year'?
I don't have exp with Java but seem #DynamoDBAttribute annotation only works on function level. So pls try
private int year;
#DynamoDBAttribute(attributeName = "release_year")
public int getYear() { return year; }
public void setYear(int year) { this.year = year; }
I found out that the annotation #JsonSetter(valueName) over the fields would suffice for my case. I can use
{
release_year: 2015
}
for my POST request, and when I use GET request, that value will be release_year instead of year like before.
I guess #DynamoDBAttribute only works for the columns in the database and does not affect the requests.
I have a model called Report having bellow two properties. I am going to retrieve the data and send it to jQuery datatable. I need to format the date field before sending it to view, I did it as bellow:
public class Report
{
public int Id {get; set;}
public DateTime ActivityDate { get; set; }
//Here is the date formation property
public string FormattedDate => ActivityDate.ToString();
}
Here is the action method which is being called by jQuery datatable:
[JQDataTable]
public ActionResult Search()
{
IQueryable<Report> data = db.Reports;
return View("Index",data);
}
The problem is, I can not get the formatted date, instead I am getting an error of:
The specified type member 'FormattedDate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
I tried and search alot but was unable to find a solution for this. In next step I want to convert this date to PersianCalendar object and return its string.
I have faced similar problems using ToString inside Linq query. For your case I think it would be easier to handle the conversion of datetime in time of view and leave the datetime variable as is. Rather accept specific format for the search action, parse the received date and do the query.
After suffering for a very long time, I now tend to accept datetime from view as string with my explicitly specified format ("yyyy-mm-dd" just my personal choice :P ) and use DateTime.TryParseExact() handling the null input as well.
Hope it helps. Happy coding.
I have a problem with date format in JSON response generated in REST project (SpringBoot+Hibernate).
When I call function I got JSON like this:
"rezerwacjaDataOd": 1535580000000,
"rezerwacjaDataDo": 1535839200000,
"rezerwacjaGodzOd": "14:00:00",
"rezerwacjaGodzDo": "12:00:00"
my entity:
private Date rezerwacjaDataOd;
private Date rezerwacjaDataDo;
private Time rezerwacjaGodzOd;
private Time rezerwacjaGodzDo;
It's Date from java.sql and Time from java.sql too
My controller:
#RestController
#CrossOrigin
#RequestMapping("api/rezerwacja")
#Api
public class RezerwacjaController {
...
#GetMapping(value = "/getRezerwacjaById")
public #ResponseBody
Rezerwacja getRezerwacjaById(Integer id) {
return rezDao.findOne(id);
}
...
Why Time is in "12:00:00" format, but Date in 1535580000000 format?
How to make Date to be in "yyyy-MM-dd" format?
You should do two things
add spring.jackson.serialization.write-dates-as-timestamps:false in your application.properties this will disable converting dates to timestamps and instead use a ISO-8601 compliant format
You can then customize the format by annotating the getter method of you dateOfBirth property with #JsonFormat(pattern="yyyy-MM-dd")
The differences in the way hibernate persists the date/time objects in the database have to do with the way these objects are used.
Per the documentation Time is a thin wrapper around Date that allows the underlying JPA provider to save the date object using the convention your noticed.
On the other hand, the Date object you pass in is converted directly to a timestamp and gets saved this way.
In both cases you can retrieve the value in question and serialize over to the desired format (with ISO-8601 being the best).
Another solution, other than the one mentioned above, is to create a custom serializer to do this.
A simple implementation would be:
public class Iso8601Serializer extends StdSerializer<Date> {
private static final String ISO_8601_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
public Iso8601Serializer() {
this(null);
}
public Iso8601Serializer(Class clazz) {
super(clazz);
}
#Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
throws IOException {
if (date == null) {
jsonGenerator.writeNull();
} else {
jsonGenerator.writeString(DateFormatUtils.format(date, ISO_8601_FORMAT));
}
}
}
Also (and this is a personal thing), I would advise in using plain Date objects to store dates and futhermore, have the respective fields annotated as #Temporal.
This question already has an answer here:
Custom json serialization for each item in IEnumerable [duplicate]
(1 answer)
Closed 4 years ago.
I'm working on a WebApi 2 service that returns data in JSON format. I use two formats for DateTimes, date: "2017-01-31" and datetime: "2017-01-31T12:00:00.000Z". The datetime format is used the most so I've set this as the default in the global.asax:
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'" });
And I use a JsonConverter attribute using a custom IsoDateTimeConverter on those DateTime fields that need to be formatted as date:
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))]
public DateTime Bar { get; set; }
}
public class OnlyDateConverter : IsoDateTimeConverter
{
public OnlyDateConverter()
{
DateTimeFormat = "yyyy-MM-dd";
}
}
So far all is fine, this works like a charm.
But here's the problem:
For some objects I have a list of DateTime objects that need to be formatted as date. But the JSON converter seems to not support using a JsonConverter attribute on a list.
public class Foo
{
[JsonConverter(typeof(OnlyDateConverter))] // This works
public DateTime Bar { get; set; }
[JsonConverter(typeof(OnlyDateConverter))] // This does not work!
public List<DateTime> Bars { get; set; }
}
This results in the following error: Unexpected value when converting date. Expected DateTime or DateTimeOffset, got System.Collections.Generic.List`1[System.DateTime].
Pretty clear, you can't use [JsonConverter(typeof(OnlyDateConverter))] on a list of dates. But then how do I format a list of DateTime as date?
I've been searching for a solution but can't seem to find anything other than creating a class that consists of just one DateTime property with the attribute. But that just doesn't seem right to me.
Surely there must be a way to use the JsonConverter attribute on a list of DateTimes? What am I missing here?
use [JsonProperty(ItemConverterType = typeof(MyDateTimeConverter))]
I have the following class....
#XmlType
#XmlRootElement(name = "milestones")
#XmlAccessorType(XmlAccessType.FIELD)
public static class Circle {
public String type = "circle";
public double cx;
public double cy;
public int r;
public String title;
public Integer width;
}
I am returning a List of Circles (actually using JaxRS with RestEasy, which uses Jackson)
I want the Json output to be like
[{"type":"circle","cx":100.0,"cy":100.0,"r":0,"title":"test1","width":2},
{"type":"circle","cx":150.0,"cy":150.0,"r":0,"title":"test2","width":0}]
and on my dev machine that is how the output looks, but on production it is like
[{"milestones":{"type":"circle","cx":100,"cy":100,"r":0,"title":"test1","width":2}},
{"milestones":{"type":"circle","cx":150,"cy":150,"r":0,"title":"test2","width":0}}]
Is there a way to force it to use the first output format (without the name listed)?
Thanks for your help,
Mason
With the same codebase its highly unlikely that the outputs are different on the two machines.
This behaviour is driven by the WRAP_ROOT_VALUE feature of the ObjectMapper, so you might want to try turning it explicitly off using the code below (you might also want to check if it is being exlicitly turned on somewhere in your code, as by default this feature is disabled)
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, false);
Since you are using RestEasy, you will need to extend the RestEasyJacksonProvider to get access to the underlying ObjectMapper.