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