1

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"
 }
}
  • Your "Test Data" looks a lot like the JSON from [How to deserialize a child object with dynamic (numeric) key names?](https://stackoverflow.com/questions/40088941/how-to-deserialize-a-child-object-with-dynamic-numeric-key-names). – dbc Nov 11 '16 at 06:48
  • Thanks, I'll try if it can be used here. –  Nov 11 '16 at 07:20
  • I've tried the solution provided in the link and it works perfectly. I've skipped WriteJson since I'm not serializing in this case. –  Nov 15 '16 at 04:45

0 Answers0