I have an endpoint that receives an DTO into the body.
The DTO has a ULong attribute that the Jackson do not parse (deserialize) when I request the
endpoint with postman.
Also, I try to create my custom serializer?
class ULongSerializer: StdSerializer<ULong>{
override fun serializer(value: ULong, gen: JsonGenarator, provader: SerializerProvider){
gen.writeStartObject()
gen.writeNumber(value) //HERE IS THE PROBLEM
gen.writeEndObject
}
}
neither write number method do not support ULong, nor another methods like write field.
Can someone give me some tips to deal with this?
ULong is a class and you may write Jackson serializer/deserializer for it, but a field of this type is compiled to bytecode as a field of primivite long type. So values exceeding Long.MAX_VALUE would be serialized/deserialized incorrectly (as negative), and custom serializer/deserializer won't help you.
Take a look at kotlinx.serialization. It have OOTB experimental support for unsigned integer types. See https://github.com/Kotlin/kotlinx.serialization/blob/master/CHANGELOG.md#experimental-support-for-inline-classes-ir-only
Related
I'd like to encode a given class of type T: EventData with Kotlinx Serialization encodeToString.
This is my code:
class EventDispatcher<T: EventData>(
val pubSubTemplate: PubSubTemplate
) {
/**
* Dispatch an event to the game engine event manager pipeline
*/
fun dispatchEvent(event: T, initiator: String) {
val eventData: String = Json.encodeToString(event)
}
The compiler tells me:
Cannot use `T` as reified type parameter. Use a class instead
Is there a way to make this still work?
For Json.encodeToString(event) to work, it needs the type information for T. But, this type information is lost at runtime due to the way how generics work in Kotlin/Java.
One way to retain the type information would be by making dispatchEvent an inline function with T as a reified type parameter.
However, this also raises the question how you want to serialize event. You could also use polymorphic serialization of EventData, rather than trying to serialize T. This will include an additional class discriminator in your serialized output (it necessarily has to for polymorphic serialization/deserialization to work).
If you serialize the concrete type T, this class discriminator wouldn't be included, which is questionable; how would whoever will deserialize this know what type it is?
In short, I think you need polymorphic serialization.
Can I somehow limit the usage of incoming enum with kotlin language features?
I have an enum, for example
enum class Message {
NORMAL,
URGENT,
LETHAL
}
When i get an incoming dto, i need to assure that it contains only URGENT or LETHAL enum values. I'm a bit lazy to write a validator, so could anyone advice some kotlin magick for that case?
Simple require assertion:
val message = Message.NORMAL
require(message in listOf(URGENT, LETHAL)) { "Message must be either urgent or lethal" }
I've got a C++/CLI layer that I've been using successfully for a long time. But I just discovered something that makes me think I need to relearn some stuff.
When my C++/CLI functions receive an instance of any managed class, they use the "hat" operator ('^') and when they receive an instance of a managed struct, they do not. I thought this was how I was supposed to write it.
To illustrate as blandly as I can
using Point = System::Windows::Point;
public ref class CppCliClass
{
String^ ReturnText(String^ text) { return text; } // Hat operator for class
Point ReturnStruct(Point pt) { return pt; } // No hat operator for struct
};
I thought this was required. It certainly works. But just today I discovered that CancellationToken is a struct, not a class. My code accepts it with a hat. I thought it was a class when I wrote it. And this code works just fine. My cancellations are honored in the C++/CLI layer.
void DoSomethingWithCancellation(CancellationToken^ token)
{
// Code that uses the token. It works just fine
}
So apparently I can choose either method.
But then what is the difference between passing in a struct by value (as I've done with every other struct type I use, like Point) and by reference (as I'm doing with CancellationToken?). Is there a difference?
^ for reference types and without for value types matches C#, but C++/CLI does give you more flexibility:
Reference type without ^ is called "stack semantics" and automatically tries to call IDisposable::Dispose on the object at the end of the variable's lifetime. It's like a C# using block, except more user-friendly. In particular:
The syntax can be used whether the type implements IDisposable or not. In C#, you can only write a using block if the type can be proved, at compile time, to implement IDisposable. C++/CLI scoped resource management works fine in generic and polymorphic cases, where some of the objects do and some do not implement IDisposable.
The syntax can be used for class members, and automatically implements IDisposable on the containing class. C# using blocks only work on local scopes.
Value types used with ^ are boxed, but with the exact type tracked statically. You'll get errors if a boxed value of a different type is passed in.
I'm writing a multithreaded program in the D programming language, but am pretty new to the language. There is a restriction on types passed between threads using the Tid.send() and receive[Only]() APIs in the std.concurrency package that they must be value types or must be constant to avoid race conditions between the sender and receiver threads. I have a simple struct Message type that I have been passing by value:
enum MessageType {
PrepareRequest,
PrepareResponse,
AcceptRequest,
Accepted
}
struct Message {
MessageType type;
SysTime timestamp;
uint node;
ulong value;
}
However, some MessageTypes don't have all the fields, and it's annoying to use a switch statement and remember which types have which fields when I could use polymorphism to do this work automatically. Is using an immutable class hierarchy recommended here, or is the approach I'm already using the best way to go, and why?
Edit
Also, if I should use immutable classes, what's the recommended way to create immutable objects of a user-defined class? A static method on the class they come from that casts the return value to immutable?
As a rule of a thumb, if you have a polymorphic type hierarchy, classes are the tool to use. And if mutation is out of the question by design, immutable classes should do the trick efficiently.
Great presentation from DConf2013 by Ali has been published recently : http://youtu.be/mPr2UspS0fE . It goes through topic of usage of const and immutable in D in great detail. Among the other good stuff it suggests to use
auto var = new immutable(ClassType)(...); syntax for creating immutable classes. All initialization goes to constructor then and no special hacks are needed.
I'm not 100% sure what the correct terminologies are but..
I have a class called InParams with two fields, a string and a long and their corresponding Property accessors to the fields. These are decorated with [DataContract] and [DataMember] respectively.
I have a WCF service method called void Test(InParams inParams)
The proxy generated fine with svcutil and I was able to set the long field, however when the service method is execute the long field is always 0, even though I explicitly set the long field. I looked at the soap envelope and don't see a tag for my long field.
When I change the long field to a string field it gets serialized. This is the same for ints as well.
Am I missing an attribute or something?
can you post a sample? double check to:
ensure class has [DataContract()] decoration
ensure PUBLIC properties have [DataMember()] decoration
Ensure your proxy class is up to date by removing/regenerating it. See if that makes a difference?
If you have a boolean YourPropertyNameSpacified property on the client in addition to YourPropertyName, you must set it to true on the client. This goes for all fields of value type, I believe. Also see WCF service proxy not setting "FieldSpecified" property.
In addition to doing what Tanner mentioned, longs and ints are clearly supported by the DataContractSerializer.
.NET Framework primitive types. The following types built into the .NET Framework can all be serialized and are considered to be primitive types: Byte, SByte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Boolean, Char, Decimal, Object, and String.Link