How to get the name of from generic type and pass it into JsonProperty()?

前端 未结 3 1867
盖世英雄少女心
盖世英雄少女心 2020-12-06 10:40

I get the following error with the code below:

\"An object reference is required for the non-static field, method, or property \'Response.PropName\'

3条回答
  •  爱一瞬间的悲伤
    2020-12-06 11:39

    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.

提交回复
热议问题