Home > OS >  Newtonsoft deserialize to object that has original string automaticaly
Newtonsoft deserialize to object that has original string automaticaly

Time:10-04

I'm trying to automate these two lines that it would be done automaticaly for types with OriginalString property: Newtonsoft's

var foo = JsonConvert.DeserializeObject<Foo>(fooAsString)
foo.OriginalString = fooAsString;

CodePudding user response:

you need something like this (you can convert it to exstension as well)

    var origString = "...";
    Foo foo = DeserializeObject<Foo>(origString);

public T DeserializeObject<T>(string json) where T :  IOriginalString,new()
{
    T foo = JsonConvert.DeserializeObject<T>(json);
    foo.OriginalString = json;
    return foo;
}

public interface IOriginalString
{
    public string OriginalString { get; set; }
}

public class Foo : IOriginalString
{
    public string OriginalString { get; set; }
}
  • Related