Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

c# - Serialize/Deserialize dynamic property name using JSON.NET

I have the following class:

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

I would like to serialize/deserialize the value for Source from the JSON field named the value of Type, for example:

{
    "type": "bank",
    "bank": "Some value"
}

or

{
    "type": "card",
    "card": "Some value"
}

Where both bind to the Source property.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...