Serialize/Deserialize dynamic property name using JSON.NET

后端 未结 3 793
春和景丽
春和景丽 2020-12-20 00:15

I have the following class:

public class MyRequest
{
    public string Type {get;set;}
    public string Source {get;set;}
}

I would like t

3条回答
  •  粉色の甜心
    2020-12-20 01:01

    You could create a custom JsonConverter to handle the dynamic property name:

    public class MyRequestConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(MyRequest);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jo = JObject.Load(reader);
            string type = (string)jo["type"];
            MyRequest req = new MyRequest
            {
                Type = type,
                Source = (string)jo[type ?? ""]
            };
            return req;
        }
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            MyRequest req = (MyRequest)value;
            JObject jo = new JObject(
                new JProperty("type", req.Type),
                new JProperty(req.Type, req.Source));
            jo.WriteTo(writer);
        }
    }
    

    To use the converter, add a [JsonConverter] attribute to your class like this:

    [JsonConverter(typeof(MyRequestConverter))]
    public class MyRequest
    {
        public string Type { get; set; }
        public string Source { get; set; }
    }
    

    Here is a working round-trip demo: https://dotnetfiddle.net/o7NDTV

提交回复
热议问题