Home > Net >  How can I create a custom converter similar to Newtonsoft using system.text.json?
How can I create a custom converter similar to Newtonsoft using system.text.json?

Time:05-28

I recently spent a lot of time upgrading my old asp.net 4.6 project to .Net 6.

I have almost everything working, but I am having trouble using System.Text.Json in place of Newtonsoft.

In my Startup.cs I ham trying to use a Custom Converter like this:

services.AddMvc()
    .AddJsonOptions(opts => {
        //custom converter for PlayerItemDto
        opts.JsonSerializerOptions.Converters.Add(new PlayerItemConverter());
    });
    
    

Here is where I am trying to do the conversion. This is all Newtonsoft now, and I am not sure if this will work in System.Text.Json.

Specifically, I can't find anything in System.Text.Json that replaces var obj = JObject.Load(reader); and options.Populate(obj.CreateReader(), retval)

Does anyone know if it's possible?

Here is my converter class:

public class PlayerItemConverter : CustomCreationConverter<PlayerItemDto>
{
    public PlayerItemDto Create(String morality)
    {
        switch (morality) {
            case "bad":
                return new MonsterTypeDto();
            case "good":
                return new LeaderTypeDto();
        }
    }

    public override Object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var obj = JObject.Load(reader);
        var morality = (String) obj.Property("morality");
        var retval = Create(morality);
        serializer.Populate(obj.CreateReader(), retval);
        return retval;
    }
}

CodePudding user response:

Your converter needs to derive from JsonConverter, and the implement CanConvert, Read and Write e.g.:

public class PlayerItemConverter : JsonConverter<PlayerItemDto>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return typeof(PlayerItemDto).IsAssignableFrom(typeToConvert);
    }   

    public override PlayerItemDto Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        using (JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader))
        {
            // Convert your jsonDoc into a PlayerItemDto and return it
        }
    }

    public override void Write(Utf8JsonWriter writer, PlayerItemDto value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, value, options);
    }
    
}

You can then either register your converter, or declare it using an attribute on the class, e.g.:

[JsonConverter(typeof(PlayerItemConverter))]
public class PlayerItemDto
{
}

UPDATE

Considering classes:

public class PlayerItemDto
{
    public string Name { get; set; }
    public int Age { get; set; }
    public AddressDto Address { get; set; }
}

public class AddressDto
{
    public int HouseNumber { get; set; }
    public string Street { get; set; }
}

You can access properties using:

using (JsonDocument jsonDoc = JsonDocument.ParseValue(ref reader))
{
    string name = jsonDoc.RootElement.GetProperty("Name").GetString();
    int age = jsonDoc.RootElement.GetProperty("Age").GetInt32();
    int houseNumber = jsonDoc.RootElement.GetProperty("Address").GetProperty("HouseNumber").GetInt32();
    string street = jsonDoc.RootElement.GetProperty("Address").GetProperty("Street").GetString();

    // Build your PlayerItemDto from the properties
}
  • Related