I have two classes in .Net Core
The class Ownership
namespace CustomStoreDatabase.Models
{
public class Ownership
{
public string OwnershipId { get; set; }
public List<string> TextOutput { get; set; }
public DateTime DateTime { get; set; }
public TimeSpan MeanInterval { get; set; }// Like long ticks, TimeSpan.FromTicks(Int64), TimeSpan.Ticks
}
}
I need to show MeanInterval
like long ticks, using the methods TimeSpan.FromTicks(Int64)
and TimeSpan.Ticks
.
My custom JsonConverter
using CustomStoreDatabase.Models;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace CustomStoreDatabase.Util
{
public class OwnershipJSonConverter : JsonConverter<Ownership>
{
public override bool CanConvert(Type typeToConvert)
{
return true;
}
public override Ownership Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.StartObject)
{
throw new JsonException();
}
//*******************
// HOW TO IMPLEMENT?
//*******************
//throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, Ownership value, JsonSerializerOptions options)
{
writer.WriteStartObject();
if (value != null)
{
writer.WriteString("OwnershipId", value.OwnershipId);
writer.WriteString("TextOutput", JsonSerializer.Serialize(value.TextOutput));
writer.WriteString("DateTime", JsonSerializer.Serialize(value.DateTime));
if (value.MeanInterval != null)
{
writer.WriteNumber("MeanInterval", (long)value.MeanInterval.Ticks);
}
else
{
writer.WriteNull("MeanInterval");
}
}
writer.WriteEndObject();
}
}
}
I don't know how to implement the Read
method.
How can I implement the custom Deserialization overriding the Read method?
If is possible you guys proposal to me another implementation for CanConvert
method, I thank you very much.
Ownership
model to addSystem.Text.Json
attributes, or is the model effectively read-only for the purposes of this question? – Indefinite