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.
Related
I'm building a relatively simple Get-method in an ASP.NET Core (3+) application. (Currently 3.1 - to be migrated to 5)
The object I need to return looks like this:
public class Data
{
public int ID { get;set;}
public string Name { get;set;}
public string Settings { get; set;}
}
And the Get-method is simply this:
public IActionResult<Data> GetData()
{
var data = _dbContext.GetData<Data>();
return Ok(data);
}
This works perfectly - except for one thing.
In SQL - the settings column (varchar(8000)), contains JSON data. In some cases, a setting can be something simple like : { "threshold": 8754 } and sometimes it can be a large complex object with many fields, but it is always valid Json.
On the ASP side, it does exactly what you would expect. It turns a serialized Json object that contains an INT and 2 x strings.
I would like for it to return an INT, ONE String and One Json Object.
Is there any way that I can tell the serializer that the Settings-property contains Json?
In a perfect world, I would love something like this:
public class Data
{
public int ID { get;set;}
public string Name { get;set;}
[SerializeContentAsJson]
public string Settings { get; set;}
}
Is there a way to do this or is there some other fairly elegant solution to this problem?
Btw. I fully realize that the caller can specify the content types that he/she will accept. In this case, the API is purely for use inside my team and we will always want JSON, so I can compromise on this being a relatively custom solution that might not work if you wanted text/html or some other content type.
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.
Can I use complex types as query string params for the HttpGet request in Asp.NET Core MVC app?
I had a problem with it, when i try to pass the param as complex type, like this:
[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int scope [FromQuery] ReportFilterMetadataDto filters)
{
...
}
all of properties in filters objects have null value. But if I pass filters like string and deserialize it into destination type, like this:
[Route("reportData")]
[HttpGet]
public List<dynamic> GetReportData(int reportId, int, string filters)
{
var result = JsonConvert.DeserializeObject<ReportFilterMetadataDto>(filters);
}
there are no problems. Is it necessary to implement custom serializer or configure asp net core app MVC, or use middleware to getting correct result. Maybe I done anything in the wrong way?
They are probably null due to a binding failure.
Try the following:
[HttpGet("reportData/{reportId}/{scope}")]
public List<dynamic> GetReportData(int reportId, int scope [FromQuery]
ReportFilterMetadataDto filters)
{
...
}
You can also have multiple FromQuery attributes. However, with the amount of information you are getting, maybe consider this method as Post and send get the dto FromBody.
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;
}
...
}