Начиная с неизменяемости, я хочу сериализовать какой-либо объект. Вот некоторые результаты и проблемы.
- Пример: отсоединение ключей от примитивных типов
Код: Выделить всё
record MyKey(Guid Value);
record MyObject(MyKey Id, string Name);
Код: Выделить всё
{
"Id": {
"Value": "2f1a3221-132a-483c-ba8b-ae94bcf56a57"
},
"Name": "My Name"
}
Код: Выделить всё
[JsonConverter(typeof(MyKeyConverter))]
record MyKey(Guid Value);
record MyObject(MyKey Id, string Name);
class MyKeyConverter : JsonConverter
{
public override MyKey Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, MyKey value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.Value);
}
}
< /code>
А теперь я ожидаю < /p>
{
"Id": "74da9c50-b824-4637-ac91-6e9f160bfdd8",
"Name": "My Name"
}
< /code>
Все было так хорошо до сих пор. Теперь у меня есть новая структура, где я добавил запись с двумя свойствами: < /p>
[JsonConverter(typeof(MyKeyConverter))]
record MyKey(Guid Value);
record AmountPayed(string Currency, decimal Value);
record MyObject(MyKey Id, string Name, AmountPayed AmountPayed);
Код: Выделить всё
{
"Id": "9bf6cd0a-3274-4663-82fc-3b26ecb6c8e0",
"Name": "My Name",
"AmountPayed": {
"Currency": "EUR",
"Value": 1000
}
}
Код: Выделить всё
[JsonConverter(typeof(MyKeyConverter))]
record MyKey(Guid Value);
[JsonConverter(typeof(AmountPayedConverter))]
record AmountPayed(string Currency, decimal Value);
record MyObject(MyKey Id, string Name, AmountPayed AmountPayed);
class MyKeyConverter : JsonConverter
{
public override MyKey Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, MyKey value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.Value);
}
}
class AmountPayedConverter : JsonConverter
{
public override AmountPayed Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, AmountPayed value, JsonSerializerOptions options)
{
writer.WriteString("Currency", value.Currency);
writer.WriteNumber("Amount", value.Value);
}
}
{
"Id": "0748f992-4187-4006-98ed-d5cb0355f99c",
"Name": "My Name",
"AmountPayed":
"Currency": "EUR",
"Amount": 1000
}
< /code>
Это даже не действительный JSON. Почему сериализация добавляет поле «рассыпанное»? Что я могу сделать, чтобы сериализовать правильный json?>
Подробнее здесь: https://stackoverflow.com/questions/793 ... in-c-sharp