I get the following error with the code below:
\"An object reference is required for the non-static field, method, or property \'Response.PropName\'
Here's a potentially easier way to achieve it. All you need to do is to have Response extend JObject, like this:
public class Response: Newtonsoft.Json.Linq.JObject
{
private static string TypeName = (typeof(T)).Name;
private T _data;
public T Data {
get { return _data; }
set {
_data = value;
this[TypeName] = Newtonsoft.Json.Linq.JToken.FromObject(_data);
}
}
}
If you do that, the following would work as you expect:
static void Main(string[] args)
{
var p1 = new Response();
p1.Data = 5;
var p2 = new Response();
p2.Data = "Message";
Console.Out.WriteLine("First: " + JsonConvert.SerializeObject(p1));
Console.Out.WriteLine("Second: " + JsonConvert.SerializeObject(p2));
}
Output:
First: {"Int32":5}
Second: {"String":"Message"}
In case you can't have Response extend JObject, because you really need it to extend Response, you could have Response itself extend JObject, and then have Response extend Response as before. It should work just the same.