将反序列化的System.Text.Json数据导入到当前类型中



我想从作为反序列化目标的类中导入json数据。在没有额外映射的情况下,System.Text.Json是否可以实现这一点?理想情况下,我会使用";这个";而不是泛型类型参数。我知道这是不可能的,但有类似的选择吗?这是我的测试代码,它是有效的,因为它创建数据对象只是为了将其映射到属性。理想情况下,我不需要实例化";测试";两次

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);

您可以尝试类似的东西

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

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; }
}

如果类没有很多属性,那么也可能是这样

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;
}
}

最新更新