Search code examples
c#jsonjson-deserializationsystem.text.json

Import deserialized System.Text.Json data into current type


I want to import json data from within the class which is the target of the deserialization. Is this possible with System.Text.Json without additional mapping? Ideally I would use "this" instead of the generic type parameter. I know that is impossible, but is there a similar option? Here is my test code which works, because it creates the data object only to map it to the property. Ideally, I would not need to instantiate "Test" twice.

public class Test
{
    public string? Bar { get; set; }
    
    public void ImportJson(string payload)
    {
        var data = System.Text.Json.JsonSerializer.Deserialize<Test>(payload);
        Bar = data?.Bar; // Don't want to map
    }
}

string foo = "{ \"Bar\": \"baz\" }";
var t = new Test();
t.ImportJson(foo);
Console.WriteLine(t.Bar);

Solution

  • you can try something like this

        string foo = "{ \"Bar\": \"baz\" }";
        var t = new Test();
        t.Deserialize(foo);
    
        Console.WriteLine(t.Instance.Bar);
    

    classes

    public static class Util
    {
        public static void Deserialize<T>(this T obj, string json) where T : IImportJson<T>
        {
            obj.Instance=System.Text.Json.JsonSerializer.Deserialize<T>(json);
        }
    }
    
    public class Test : ImportJson<Test>
    {
        public string? Bar { get; set;}
        
    }
    
    public interface IImportJson<T>
    {
        public T Instance { get; set; }
    }
    public class ImportJson<T>: IImportJson<T>
    {
        public T Instance { get; set; }
    }
    

    if class dosn't have many properies, it could be like this too

    public interface IImportJson<T>
    {
        public void ImportJson (T obj);
    }
    public class Test : IImportJson<Test>
    {
        public string? Bar { get; set; }
        
        public void ImportJson(Test test)
        {
            Bar=test.Bar;
        }
    }