使用JSON.NET序列化/反序列化动态属性名称 [英] Serialize/Deserialize dynamic property name using JSON.NET

查看:452
本文介绍了使用JSON.NET序列化/反序列化动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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

我想从名为Type的值的JSON字段对Source的值进行序列化/反序列化,例如:

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"
}

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

两者都绑定到Source属性.

推荐答案

您可以创建自定义

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);
    }
}

要使用转换器,请在类中添加[JsonConverter]属性,如下所示:

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; }
}

这是一个有效的往返演示: https://dotnetfiddle.net/o7NDTV

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

这篇关于使用JSON.NET序列化/反序列化动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆