Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic JContainer (JSON.NET) & Iterate over properties at runtime

Tags:

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?

like image 230
Alex Avatar asked Nov 30 '12 20:11

Alex


People also ask

How to get the elements of a dynamic JSON file?

dynamic json = new JDynamic (" [1,2,3]"); /json.Length/json.Count is 3 //And you can use json [0]/ json [2] to get the elements dynamic json = new JDynamic (" {a: [1,2,3]}"); //json.a.Length /json.a.Count is 3.

Is it possible to deserialize JSON into a dynamic object?

Another important thing is that we should avoid using ExpandoObject for such purposes. Conclusion In this article, we have explored a few ways to deserialize JSON into a dynamic object. In the end, our performance analysis shows that System.Text.Jsonperforms better than Newtonsoft.Jsonin general. Share: PreviousLINQ Basic Concepts in C#

What happened to dynamic JSON parsing in web API?

I wrote about dynamic JSON parsing a few months back before JSON.NET was added to Web API and when Web API and the System.Net HttpClient libraries included the System.Json classes like JsonObject and JsonArray. With the inclusion of JSON.NET in Web API these classes are now obsolete and didn't ship with Web API or the client libraries.

What is a JSON object?

Rather the JSON.NET objects are the containers that receive the data as I build up my JSON structure dynamically, simply by adding properties. This means this code can be entirely driven at runtime without compile time restraints of structure for the JSON output.


1 Answers

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()); 
like image 200
L.B Avatar answered Oct 03 '22 15:10

L.B