Search code examples
c#jsonkeyvaluepairexpandoobject

Convert List<ExpandoObject> to List<KeyValuePair>


I'm currently working on a .NET Framework 4.7.2 application. From a web service response, I need to parse JSON data to a List<KeyValuePair<int, Dictionary<string, object>>>. This datatype is important for the further program flow, I cannot change it.

The JSON data with dynamic properties looks like that:

{ "data" : [
   {"Id":1, Text:"Test1", coolProp: 213 },
   {"Id":2, Text:"Test2"},
   {"Id":3, Text:"Test3", otherProp: "cool" },
]}

I tried the following coding, but it didn't work:

JsonConvert.DeserializeObject<List<KeyValuePair<int, Dictionary<string, object>>>>(Convert.ToString(JObject.Parse(json)["data"]));

On the other hand i can convert the json to an ExpandoObject:

var expando = JsonConvert.DeserializeObject<List<ExpandoObject>>(Convert.ToString(JObject.Parse(json)["data"]));

I'm thought about writing a private method to convert the ExpandoObject into my List<KeyValuePair<int, Dictionary<string, object>>>.

private KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>> ConvertExpandoToKeyValue(float key, List<ExpandoObject> expando)
{
    var result = new KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>>();

    // I don't really know how to convert the expando object to the desired data structure
    // Moreover I need to put a float key in the structure: 52.2343

    return result;
}

The ExpandoObject looks like this:

enter image description here

The final result a KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>> should look like that:

enter image description here

Do you know how to convert the ExpandoObject to the desired data type and add a key at the beginning?

Or perhaps, do you know a better way to convert the JSON data to my desired data structure?

Thank you very much!!


Solution

  • Ok, I wrote a solution, I just wanted to share with you. Perhaps there is a better way though:

    private KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>> ConvertExpandoToKeyValue(float key, List<ExpandoObject> expando)
    {
        var result = new KeyValuePair<float, List<KeyValuePair<int, Dictionary<string, object>>>>
            (key, new List<KeyValuePair<int, Dictionary<string, object>>>());
    
        for (int i = 0; i < expando.Count; i++)
        {
            var element = new Dictionary<string, object>(expando[i]);
    
            var propertyValues = new KeyValuePair<int, Dictionary<string, object>>(i, element);
    
            result.Value.Add(propertyValues);
        }
    
        return result;
    }