I am trying to serialize a class with a generic property using the MessagePack-CSharp package. Here's a minimum reproducible example of what I'm trying to do:
using MessagePack;
[MessagePackObject(keyAsPropertyName: true)]
public class Data<T>
{
T data { get; set; }
public Data(T data)
{
this.data = data;
}
}
Data<int> testData = new(1);
byte[] bytes = MessagePackSerializer.Serialize(testData);
Console.WriteLine(MessagePackSerializer.ConvertToJson(bytes));
That program, as written, will throw an exception about not being able to find a matched constructor. If I add a parameterless constructor with an empty body, it no longer throws -- but will return {}
as the converted JSON, when I really want { "data": 1 }
. Is it possible to accomplish this?
CodePudding user response:
I was being really stupid, I need to specify public T data { get; set; }
. Alternatively the MessagePack-CSharp README has information about how to tell the serializer to target private fields.