-1
{  
"Jhone":[  
  {  
     "Key":"Employeename",
     "Value":"Jhone"
  },
  {  
     "Key":"Address",
     "Value":[  
        {  
           "Key":"City",
           "Value":"Newyork"
        },
        {  
           "Key":"Country",
           "Value":"USA"
        }
     ]
  }
],
"Mohamed":[  
  {  
     "Key":"Employeename",
     "Value":"Mohamed"
  },
  {  
     "Key":"Address",
     "Value":[  
        {  
           "Key":"City",
           "Value":"Delhi"
        },
        {  
           "Key":"Country",
           "Value":"india"
        }
     ]
  }
]
}

This is my JSON format. How to convert in to ExpandoObject in c#? Here is my code as

using System.Dynamic;
using System.Web.Script.Serialization;
using System.IO;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

var ictionarys = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(value);
foreach (var item in ictionarys)
{
List<object> itemList = new List<object>();

foreach (var item2 in (ICollection)item.Value)
{
   //Here how to code
}                   
Console.WriteLine(item.Key + "=> " + item.Value);
}
R15
  • 13,982
  • 14
  • 97
  • 173
Veeramani
  • 19
  • 1
  • 7
  • 1
    Could you give more information about why you specifically want `ExpandoObject`? If you just want a dynamic way of accessing the JSON, have you tried just using `JObject`? (`dynamic obj = JObject.Parse(value);` and then work from there...) – Jon Skeet Aug 06 '18 at 12:54
  • 1
    Json.NET supports deserializing to `ExpandoObject` directly, as mentioned in https://www.newtonsoft.com/json/help/html/SerializationGuide.htm#Dynamic. Have you tried it? See e.g. [Deserialize Dynamic Json string using Newtonsoft JSON.NET](https://stackoverflow.com/q/22906010/3744182) – dbc Aug 06 '18 at 13:02
  • @Daisy Shipton, Thank you. But when we Address Key, That value is as Json. How to change inner JObject.parse(value) – Veeramani Aug 06 '18 at 13:15
  • `var expando = JsonConvert.DeserializeObject(value);` just works, see https://dotnetfiddle.net/ZEPkye for a demo. What is your problem? – dbc Aug 06 '18 at 19:50
  • I'm afraid I don't understand what you mean in your comment. Yes, you'd need to find the object that has a "Key" property with a value of "Address", due to the way your JSON is structured... you could easily create a `Dictionary` if that's more useful. – Jon Skeet Aug 07 '18 at 01:41

1 Answers1

0

Maybe you can use this extension method

public static ExpandoObject Expando(this IEnumerable<KeyValuePair<string, object>> dictionary)
{
    var expando = new ExpandoObject();
    var expandoDic = (IDictionary<string, object>)expando;
    foreach (var item in dictionary)
    {
        expandoDic.Add(item);
    }
    return expando;
}

Method return ExpandoObject with key,value list

devowiec
  • 708
  • 6
  • 16