I get the following error with the code below:
\"An object reference is required for the non-static field, method, or property \'Response.PropName\'
@Thomas Levesque: OK. So let's say that you can't extend JObject in Response because you need to extend a pre-existing Response class. Here's another way you could implement the same solution:
public class Payload : 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);
}
}
}
//Response is a pre-existing class...
public class Response: Response {
private Payload Value;
public Response(T arg) {
Value = new Payload() { Data = arg };
}
public static implicit operator JObject(Response arg) {
return arg.Value;
}
public string Serialize() {
return Value.ToString();
}
}
So now there are the following options to Serialize the class:
static void Main(string[] args) {
var p1 = new Response(5);
var p2 = new Response("Message");
JObject p3 = new Response(0.0);
var p4 = (JObject) new Response(DateTime.Now);
Console.Out.WriteLine(p1.Serialize());
Console.Out.WriteLine(p2.Serialize());
Console.Out.WriteLine(JsonConvert.SerializeObject(p3));
Console.Out.WriteLine(JsonConvert.SerializeObject(p4));
}
The Output will look something like this:
{"Int32":5}
{"String":"Message"}
{"Double":0.0}
{"DateTime":"2016-08-25T00:18:31.4882199-04:00"}