1

I receive data from a provider and it can look like:

{
    "data": [
        {
            "propertyNames":[
                {
                    "a":"a1",
                    "b":"b1",
                    ...
                    "z":"z1"
                },
                {
                    "a":"a2",
                    "b":"b2",
                    ...
                    "z":"z2"
                },
            ],
            ...
            "otherProperty": "abc"
        },
        {
            "propertyNames":{
                "1": {
                    "a":"a1",
                    "b":"b1",
                    ...
                    "z":"z1"
                },
                "2": {
                    "a":"a2",
                    "b":"b2",
                    ...
                    "z":"z2"
                },
            },
            ...
            "otherProperty": "bce"
        }
    ]
}

So effectively, propertyNames can be the following types:

[JsonProperty("propertyNames")]
Dictionary<string, MyObject> PropertyNames {get;set;}

[JsonProperty("propertyNames")]
List<MyObject> PropertyNames {get;set;}

How can I deserialize this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
dyesdyes
  • 1,147
  • 3
  • 24
  • 39
  • Can you add in the wich result type of deserialization and some use case? – Support Ukraine Apr 04 '20 at 19:46
  • is better structuring your JSON an option? – Franz Gleichmann Apr 04 '20 at 19:56
  • @FranzGleichmann It is coming from a provider so no – dyesdyes Apr 04 '20 at 20:18
  • Related: [Display JSON object array in datagridview](https://stackoverflow.com/q/41553379/3744182). In fact if we assume that the property names are all integers I think the converter `ListToDictionaryConverter` from [this answer](https://stackoverflow.com/a/41559688/3744182) might just work for you, since its `ReadJson()` checks for the incoming JSON being either an array or an object. – dbc Apr 04 '20 at 20:31
  • Your JSON is not well-formed. The second `"propertyNames"` value needs to be delimited by `{` and `}` not `[` and `]`. But if I fix that then `[JsonConverter(typeof(ListToDictionaryConverter))]` works, see https://dotnetfiddle.net/kHcBaw. Mark as a duplicate? – dbc Apr 04 '20 at 20:39
  • Or, would you prefer that the underlying data model be a `Dictionary` instead of `List`? If so the converter will need to be modified. – dbc Apr 04 '20 at 20:46
  • This is perfect, just tested it and it works like a charm. Can you transform it into a response please? – dyesdyes Apr 04 '20 at 20:47

2 Answers2

2

There are multiple choices really how you can approach this.

For example you can use JObject as a type

[JsonProperty("propertyNames")]
JObject PropertyNames {get;set;}

Unfortunately you would have to write down complex logic to parse information out of that.

You can also create custom JsonConverter

public class DynamicTypeConverter: JsonConverter<DynamicType>
{
    public override void WriteJson(JsonWriter writer, Version value, JsonSerializer serializer)
    {
    }

    public override DynamicType ReadJson(JsonReader reader, Type objectType, Version existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var obj = new DynamicType();
        // Least fun part, compute & assign values to properties
        // Logic depends if you are going to use JObject.Load(reader) or reader.Read() with reader.Value and TokenType
        return obj;
    }
}

public class DynamicType
{
  Dictionary<string, MyObject> PropertyNamesDict {get;set;}
  List<MyObject> PropertyNamesList {get;set;}
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Józef Podlecki
  • 10,453
  • 5
  • 24
  • 50
2

Assuming that the property names inside the "propertyNames" object are all integers, you can define your data model as follows, using ListToDictionaryConverter<T> from this answer to Display JSON object array in datagridview:

The data model:

public class MyObject
{
    public string a { get; set; }
    public string b { get; set; }
    public string z { get; set; }
}

public class Datum
{
    [JsonConverter(typeof(ListToDictionaryConverter<MyObject>))]
    public List<MyObject> propertyNames { get; set; }
    public string otherProperty { get; set; }
}

public class RootObject
{
    public List<Datum> data { get; set; }
}

The converter is copied as-is with no modification. It transforms the JSON object

{
   "1":{
      "a":"a1",
      "b":"b1",
      "z":"z1"
   },
   "2":{
      "a":"a2",
      "b":"b2",
      "z":"z2"
   }
}

into a List<MyObject> with values at indices 1 and 2, and null at index zero.

Demo fiddle #1 here.

Alternatively, if you would prefer your propertyNames to be of type Dictionary<int, MyObject>, you can modify the model and converter as follows:

public class Datum
{
    [JsonConverter(typeof(IntegerDictionaryToListConverter<MyObject>))]
    public Dictionary<int, MyObject> propertyNames { get; set; }
    public string otherProperty { get; set; }
}

public class IntegerDictionaryToListConverter<T> : JsonConverter where T : class
{
    // From this answer https://stackoverflow.com/a/41559688/3744182
    // To https://stackoverflow.com/questions/41553379/display-json-object-array-in-datagridview
    public override bool CanConvert(Type objectType)
    {
        return typeof(Dictionary<int, T>).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.Null)
            return null;
        var dictionary = existingValue as IDictionary<int, T> ?? (IDictionary<int, T>)serializer.ContractResolver.ResolveContract(objectType).DefaultCreator();
        if (reader.TokenType == JsonToken.StartObject)
            serializer.Populate(reader, dictionary);
        else if (reader.TokenType == JsonToken.StartArray)
        {
            var list = serializer.Deserialize<List<T>>(reader);
            for (int i = 0; i < list.Count; i++)
                dictionary.Add(i, list[i]);
        }
        else
        {
            throw new JsonSerializationException(string.Format("Invalid token {0}", reader.TokenType));
        }
        return dictionary;
    }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Demo fiddle #2 here.

If the property names aren't always integers you can modify the converter slightly to deserialize to a Dictionary<string, T>.

dbc
  • 104,963
  • 20
  • 228
  • 340