Deserialize nested JSON in a flat class using Json.NET

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 next flattened class using JsonPropertyAttribute:

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

I am trying to specify a "Navigation" rule based on /as a JSON name separator.

Basically, I want to indicate what JsonProperty("fields/issuetype/name")should be used as a navigation rule for a nested property fields.issuetype.name, which obviously doesn't work:

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

The above only recognizes Id:

Id: 10
Type:

What do I need to implement in order to tell Json.NET to use "/" as the navigation path to the desired attached property?

+4
1

-

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

All Articles