Serialize/Deserialize dynamic property name using JSON.NET

后端 未结 3 796
春和景丽
春和景丽 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 00:45

    My solution is: First create APIResultModel class:

    public class APIResultModel where T: APIModel, new()
    {
    
        public string ImmutableProperty { get; set; }
    
        public T Result { get; set; }
    
        public APIResultModel Deserialize(string json)
        {
            var jObj = JObject.Parse(json);
            T t = new T();
            var result = jObj[t.TypeName()];
            jObj.Remove(t.TypeName());
            jObj["Result"] = result;
            return jObj.ToObject>();
        }
    }
    

    Second create APIModel abstract Class:

    public abstract class APIModel
    {
        public abstract string TypeName();
    }
    

    Third create dynamic content Model class:

    public class MyContentModel: APIModel
    {
        public string Property {get; set;}
        public override string TypeName()
        {
            return "JsonKey";
        }
    }
    

    When you need to deserialize a json string:

    var jsonModel = new APIResultModel();
    jsonModel = jsonModel.Deserialize(json);
    MyContentModel dynimacModel = jsonModel.Result;
    

    The Deserialize function is come from @Eser

提交回复
热议问题