使用Json.NET将嵌套的JSON反序列化为平面类

时间:2016-02-25 13:12:52

标签: c# json json.net deserialization

给出以下嵌套的JSON字符串:

string s = @"
{
    ""id"": 10,
    ""fields"":{
        ""issuetype"": {
            ""name"": ""Name of the jira item""
        }
    }
}";

如何使用JsonPropertyAttribute将其反序列化为以下“扁平”类:

public class JiraIssue
{
    [JsonProperty("id")]
    public int Id { get; set; }
    [JsonProperty("fields/issuetype/name")]
    public string Type { get; set; }
}

我正在尝试将基于/的“导航”规则指定为JSON属性名称中的分隔符。

基本上,我想指定JsonProperty("fields/issuetype/name")应该用作嵌套属性fields.issuetype.name的导航规则,这显然不起作用:

var d = Newtonsoft.Json.JsonConvert.DeserializeObject<JiraIssue>(s);
Console.WriteLine("Id:" + d.Id);
Console.WriteLine("Type" + d.Type);

以上仅识别Id:

Id: 10
Type:

我需要实现什么来告诉Json.NET使用“/”作为所需嵌套属性的导航路径?

1 个答案:

答案 0 :(得分:3)

这是一种可能的方式 -

internal class ConventionBasedConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return typeof(JiraIssue).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var daat = JObject.Load(reader);
        var ret = new JiraIssue();

        foreach (var prop in ret.GetType().GetProperties(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance))
        {
            var attr = prop.GetCustomAttributes(false).FirstOrDefault();
            if (attr != null)
            {
                var propName = ((JsonPropertyAttribute)attr).PropertyName;
                if (!string.IsNullOrWhiteSpace(propName))
                {
                    var conventions = propName.Split('/');
                    if (conventions.Length == 3)
                    {
                        ret.Type = (string)((JValue)daat[conventions[0]][conventions[1]][conventions[2]]).Value;
                    }

                    ret.Id = Convert.ToInt32(((JValue)daat[propName]).Value);
                }                        
            }
        }


        return ret;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {

    }
}

var settings = new JsonSerializerSettings();
settings.Converters.Add(new ConventionBasedConverter());
var o = JsonConvert.DeserializeObject<JiraIssue>(s, settings);