Using Newtonsoft.Json and given the "Greeting" class below, I'm trying to allow "Message" to be de/serialized as it does now and as a string.
public class Greeting
{
public IHello Message { get; set; }
}
public interface IHello
{
string Phrase { get; set; }
}
public class Hello1 : IHello
{
public string Phrase { get; set; }
}
var greeting = new Greeting
{
Message = new Hello1
{
Phrase = "Yo!"
}
};
var jsonText = JsonConvert.SerializeObject(greeting);
Current output: {"Message":{"Phrase":"Yo!"}}
but I also want to be able to output {"Message":"Yo!"}
I did consider using a Generic
public class Greeting<T>
{
public T Message { get; set; }
}
But I didn't want the user to have to know about setting
var greeting = new Greeting<string> { Message = "" };
or
var greeting = new Greeting<Hello1> { Message = new Hello1 { Phrase = "Yo!" }};
Is it possible to achieve the desired json de/serialization in another way perhaps? Or maybe I use the implementation above but hide that away somehow?
All help is appreciated!