0

I did search on So but it looks like for this type of json serializer there isnt much info out there. I'm using original version since I need 4.5 NET target: https://github.com/neuecc/Utf8Json

I have a custom object that needs custom serialization/deserialization logic:

 public class CustomInstanceFormatter : IJsonFormatter<CustomInstance>
    {
        public void Serialize(ref JsonWriter writer, CustomInstance value, IJsonFormatterResolver formatterResolver)
        {
            if (value == null) { writer.WriteNull(); return; }

            writer.WriteString(value.name);
            formatterResolver.GetFormatterWithVerify<SomeNamespace.Data>().Serialize(ref writer, value.color, formatterResolver);
        }

        public CustomInstance Deserialize(ref JsonReader reader, IJsonFormatterResolver formatterResolver)
        {
            if (reader.ReadIsNull()) return null;
            var inst = new CustomInstance(reader.ReadString());
            inst.color = formatterResolver.GetFormatterWithVerify<SomeNamespace.Data>().Deserialize(ref reader, formatterResolver);
            return inst;
        }
    }

My problem is that the short readme does not explain anywhere how can I consume it. With NewtonSoft JSON it is fairly simple, but here I'm at a loss. JsonSerializer in both of his methods for Serialize/Deserialize only accepts a IJsonResolver.

KreonZZ
  • 175
  • 2
  • 10

1 Answers1

0

You have to create your own Resolver which consumes your Formatter like this:

public class StandardFunctionResolver : IJsonFormatterResolver
{
    public static StandardFunctionResolver Instance = new StandardFunctionResolver();
    public Dictionary<Type, IJsonFormatter> formatters;
    private StandardFunctionResolver ()
    {
        formatters = new Dictionary<Type, IJsonFormatter>()
        {
            {typeof(CustomInstance), new CustomInstanceFormatter()},
        };
    }

    public IJsonFormatter<T> GetFormatter<T>()
    {
        if (formatters.TryGetValue(typeof(T), out var typeFormatter))
        {
            return (IJsonFormatter<T>)typeFormatter;
        }

        return StandardResolver.Default.GetFormatter<T>();
    }
  }

and then let UTF8Json consume it on Serialization or Deserialization like:

var idk = Utf8Json.JsonSerializer.ToJsonString(obj, StandardFunctionResolver.Instance);
Alex Cr
  • 431
  • 5
  • 8