I've found a great many answers for deserializing, but none for the other way around.
Let's say i have this simple example class:
public class MyLogEntry {
long timestamp;
public MyLogEntry() {}
}
Now i want to serialize this using jackson and turn this timestamp in epoch time into a date string, for example "2020-05-08T09:17:15.154Z". I could do this by adding a getter method with the #JsonProperty tag, but i was wondering if this is possibly in a simpler way using JsonFormat instead.
This worked for me:
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
Of course you'd have to change your timestamp to java.util.Date().
https://fasterxml.github.io/jackson-databind/javadoc/2.6/com/fasterxml/jackson/databind/SerializationFeature.html
You could also write a custom serializer, but that would probably be overkill in this case.
Related
I'm a little confused with Optaplanner Joiners and data types. Can someone clarify what data types Joiners work on?
Specifically - will they work on LocalDateTime:
...
Joiners.lessThanOrEqual( (lesson) -> lesson.getTimeslot().getStartTime() )
...
where getStartTime() will return a LocalDateTime
of is this a case where a filter is required?
OptaPlanner Joiners supports LocalDateTime.
LocalDateTime implements equals() and hashcode(), so Joiners.equal() works even if they are not the same instance but represent the same datetime.
LocalDateTime implements Comparable, so Joiners.lessThanOrEqual() works as expected.
There's even Joiners.overlapping() to efficiently detect entities that overlap fully or partially in time. Because your model has getStartTime() and you're trying to use lessThan*, you'll need overlapping() semantics.
Note that the Collectors have some java.time specific methods like sumDuration(). But for Joiners, the general purpose ones are enough.
I have POCO classes , I use NewtonSoft json for seralization. Now i want to migrate it to Google protocol buff. Is there any way i can migrate all my classes (not manually) so that i can use google protocol buff for serialization and deseralization.
Do you just want it to work? The absolute simplest way to do this would be to use protobuf-net and add [ProtoContract(ImplicitFields = ImplicitFields.AllPublic)]. What this does is tell protobuf-net to make up the field numbers, which it does by taking all the public members, sorting them alphabetically, and just counting upwards. Then you can use your type with ProtoBuf.Serializer and it should behave in the way you expect.
This is simple, but it isn't very robust. If you add, remove or rename members it can all get out of sync. The problem here is that the protocol buffers format doesn't include names - just field numbers, and it is much harder to guarantee numbers over time. If your type is likely to change, you probably want to define field numbers explicitly. For example:
[ProtoContract]
public class Foo {
[ProtoMember(1)]
public int Id {get;set;}
[ProtoMember(2)]
public List<string> Names {get;} = new List<string>();
}
One other thing to watch out for would be non-zero default values. By default protobuf-net assumes certain things about implicit default values. If you are routinely using non-zero default values without doing it very carefully, protobuf-net may misunderstand you. You can turn that off globally if you desire:
RuntimeTypeModel.Default.UseImplicitZeroDefaults = false;
I am using Dropwizard 0.8.4 and jackson-datatype-jsr310.
a)
Would like to serialise my LocalDateTime to JSON output as DateTimeFormatter.ISO_INSTANT but could not find any clean way to do that (without implementing custom serialising classes), shouldn't this be very standard thing to do with simple annotations?
Currently my code works with:
#JsonProperty
#JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss'Z'")
#JsonSerialize(using = LocalDateTimeSerializer.class)
public LocalDateTime getTime() {
...
}
but that pattern isn't really same as ISO_INSTANT, and as I debugged it a bit, ISO_INSTANT cannot even be presented by a String-pattern.
b) Would I be better off using Joda-Time, that seems to be supported by Dropwizard by default?
c) Is there way to skip serialising Java-field into JSON based on the value (boolean being false)? I tried #JsonFilter and SimpleBeanPropertyFilter but didn't get it to work, and it seems to be deprecated as well. Also #JsonProperty(defaultValue...) didn't seem to work either.
hello i got an application that uses nhibernate as orm, i need to store data that represents time,
whats the best way to do it?
nhibenate dont know to convert time field from db to a timespan, only string.
NHibernate supports DateTime, Ticks, TimeSpan and Timestamp. Make sure you are specifying the type explicitly on your mapping element as the different time types have different semantics so what NHibernate is guessing may not be correct.
If you are and are still having problems, modify your post to include the relevant portions of your entity, mapping file, and the actual problem you are encountering.
Edit:
For example, with the following class for a TimeSpan:
public class MyClass
{
// Other properties
// ...
// ...
public virtual TimeSpan MyTimeProperty { get; set; }
}
And the mapping file:
<!-- other properties -->
<property name="MyTimeProperty" type="TimeSpan" /> <!-- Note: NH expects the DB type to be DbType.Int64 -->
You indicate that you're trying to map a TimeSpan ("nhibenate dont know to convert time field from db to a timespan, only string"). If this is the correct type matching between .NET (typeof TimeSpan) and the database (DbType.Int64), NH should do this automatically (i.e. you shouldn't need to specify type="TimeSpan"). So if it's not working, I suspect there is a problem with the way you have things setup. It may be helpful if you post the property/field declaration with full signature, the <property> line for this property from your mapping file, and the column definition from the database.
Also, make sure you use nullables for your DateTimes that can be null in database.
DateTime? instead of just DateTime.
If not, NHibernate will attempt to initialize your date to a default value which probably isn't what you want.
We are trying to force our datetime objects in c# to serialize using a different format than the default. We don't want to include milliseconds. The SortableDateTimePattern and the UniversalSortableDateTimePattern is read-only.
Assuming you're talking about DateTime instances in a DataContract being sent by the server, I don't think there's a straightforward way to do this. The patterns you mention aren't used (if they were, you could just hack the shared pattern instance via reflection for a gross-but-easy solution). The DataContractSerializer ultimately delegates the task to the internal XsdDateTime.ToString() method, which is hardcoded to always emit the fractional seconds if they're nonzero.
It's not elegant, but taking advantage of the hardcoded behavior might be the simplest solution: just copy all your DateTimes, resetting the milliseconds to zero before they leave the server.
Alternatively, you're left with hooking up a custom IDispatchMessageFormatter or IDispatchMessageInspector on the affected operations. Neither is a walk in the park if you want them to be generic and easy to hook up.
Just curious- do you have a misbehaving client that doesn't understand the fractional seconds?
I figured out a few ways to handle this problem. The more complicated methods involve hooking of a custom MessageFormatter Endpoint.
We found a simple way to to this.
the Fraction of seconds are only generated if the datetime object has them.
What we did:
We created a static on propertychange event handler that uses reflection to detect datetime datatypes. When found we recreate the datetime without the fractions of seconds. In our case we didn't care about seconds at all. We wire the event up in a partial class constructor. Thats it.
Of course
public static class DateTimeSecondCatcher
{
PropertyInfo dateTimePropertyInfo = sender.GetType().GetProperty(e.PropertyName);
if ((dateTimePropertyInfo != null) && (dateTimePropertyInfo.PropertyType == typeof(DateTime)))
{
DateTime dteValue = (DateTime)dateTimePropertyInfo.GetValue(sender, null);
if (dteValue.Millisecond > 0)
{
dateTimePropertyInfo.SetValue(sender, new DateTime(dteValue.Year,dteValue.Month,dteValue.Day, dteValue.Hour,dteValue.Minute,dteValue.Second,0,dteValue.Kind), null);
}
}
}
// This code goes in the partial class constructor
this.PropertyChanged += new PropertyChangedEventHandler(DateTimeSecondCatcher.OnPropertyChanged);