Deserialize nested JSON to a flat class using Json.NET [duplicate]

梦想的初衷 提交于 2019-12-07 09:05:48

问题


Given the following nested JSON string:

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

How can I deserialize it to the following "flattened" class, using the JsonPropertyAttribute:

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

I'm trying to specify a "navigation" rule based on / as a separator in the name of the JSON property.

Basically, I want to specify that JsonProperty("fields/issuetype/name") should be used as a navigation rule to the nested property fields.issuetype.name, which obviously does not work:

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

The above recognizes only the Id:

Id: 10
Type:

What do I have to implement to tell Json.NET to use the "/" as a navigation path to the desired nested property?


回答1:


This is One possible way -

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


来源:https://stackoverflow.com/questions/35628318/deserialize-nested-json-to-a-flat-class-using-json-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!