22

I'm receiving a JSON string in a MVC4/.NET4 WebApi controller action. The action's parameter is dynamic because I don't know anything on the receiving end about the JSON object I'm receiving.

 public dynamic Post(dynamic myobject)        

The JSON is automatically parsed and the resulting dynamic object is a Newtonsoft.Json.Linq.JContainer. I can, as expected, evaluate properties at runtime, so if the JSON contained something like myobject.myproperty then I can now take the dynamic object received and call myobject.myproperty within the C# code. So far so good.

Now I want to iterate over all properties that were supplied as part of the JSON, including nested properties. However, if I do myobject.GetType().GetProperties() it only returns properties of Newtonsoft.Json.Linq.JContainer instead of the properties I'm looking for (that were part of the JSON).

Any idea how to do this?

Alex
  • 75,813
  • 86
  • 255
  • 348
  • [this](http://code.msdn.microsoft.com/Supporting-different-data-b0351c9a) article might help you, check out what he's doing in the `DeserializeRequest` method. – Mike Christensen Nov 30 '12 at 20:54

1 Answers1

50

I think this can be a starting point

dynamic dynObj = JsonConvert.DeserializeObject("{a:1,b:2}");

//JContainer is the base class
var jObj = (JObject)dynObj;

foreach (JToken token in jObj.Children())
{
    if (token is JProperty)
    {
        var prop = token as JProperty;
        Console.WriteLine("{0}={1}", prop.Name, prop.Value);
    }
}

EDIT

this also may help you

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(jObj.ToString());
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 1
    @Alex Then things are getting complicated and you may have to write a recursive function. You should always check JObject,JArray,JProperty etc, Basically you should repeat what `JsonConvert.DeserializeObject` does. – L.B Nov 30 '12 at 21:05
  • 2
    @Alex I guess deserializing to a `Dictionary` may help also. See the edit. – L.B Nov 30 '12 at 21:13