I'm trying to deserialize a json string that has one of the property name generated dynamically (ex: 0, 1 etc) based on the no. of items.. In the JSON model, Test property name is used assigning the values of the dynamically generated onjects and i've created a custom converter to match digit and assign it to Test property.
The problem is i'm not sure how to set the values in a list because the Test property can have multiple values of same type. I want the result in an array or list.
Custom Conveter:
public class CustomPropertyNameConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
object instance = objectType.GetConstructor(Type.EmptyTypes).Invoke(null);
PropertyInfo[] props = objectType.GetProperties();
JObject jo = JObject.Load(reader);
foreach (JProperty jp in jo.Properties())
{
string name = jp.Name;
//Match digits
if (Regex.IsMatch(name, "^[0-9]*$"))
{
name = "Test"; // Here i've assigned the property name that is defined in the Json Model
}
PropertyInfo prop = props.FirstOrDefault(pi => pi.CanWrite && string.Equals(pi.Name, name, StringComparison.OrdinalIgnoreCase));
if (prop != null)
//How to add it to List of Detail type??
prop.SetValue(instance, jp.Value.ToObject(prop.PropertyType, serializer));
}
return instance;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Model
[JsonConverter(typeof(CustomPropertyNameConverter))]
public class Data
{
public int group_id { get; set; }
public Detail Test { get; set; } // Dynamic property name needs to be converted to List or Array
}
public class Detail
{
public string id { get; set; }
public string status { get; set; }
}
Test Data:
"data":
{
"group_id":2758,
"0":
{
"id": "1",
"status": "PASS"
},
"1":
{
"id": "2",
"status": "FAIL"
}
}