Deserialize the JSON where the values are field names with JSON.NET

后端 未结 3 1372
深忆病人
深忆病人 2020-12-11 06:33

I have a very undesirable situation which requires me to deserialize the JSON where the values are field names with JSON.NET. Assuming that I have the following JSON which i

3条回答
  •  庸人自扰
    2020-12-11 06:58

    You can create a custom JsonConverter which serializes/deserializes Role[]. You can then decorate your Roles property with the JsonConverterAttribute like this:

    public class User
    {
        public string Name { get; set; }
        [JsonConverter(typeof(RolesConverter))]
        public Role[] Roles { get; set; }
    }
    

    In your converter class you are able to read an object and return an array instead. Your converter class may look like this:

    class RolesConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType == typeof(Role[]);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            // deserialize as object
            var roles = serializer.Deserialize(reader);
            var result = new List();
    
            // create an array out of the properties
            foreach (JProperty property in roles.Properties())
            {
                var role = property.Value.ToObject();
                role.Id = int.Parse(property.Name);
                result.Add(role);
            }
    
            return result.ToArray();
        }
    
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }
    

提交回复
热议问题