Serialize/Deserialize dynamic property name using JSON.NET

后端 未结 3 808
春和景丽
春和景丽 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:09

    I would write custom serialization/deserialization methods

    var req1 = new MyRequest() { Type = "card", Source = "SomeValue" };
    var json = Serialize(req1);
    var req2 = Deserialize(json);
    

    string Serialize(T obj)
    {
        var jObj = JObject.FromObject(obj);
        var src = jObj["Source"];
        jObj.Remove("Source");
        jObj[(string)jObj["Type"]] = src;
        return jObj.ToString(Newtonsoft.Json.Formatting.Indented);
    }
    
    T Deserialize(string json)
    {
        var jObj = JObject.Parse(json);
        var src = jObj[(string)jObj["Type"]];
        jObj.Remove((string)jObj["Type"]);
        jObj["Source"] = src;
        return jObj.ToObject();
    } 
    

提交回复
热议问题