Converting dynamic type to dictionary C#

You can fill the dictionary using reflection: public Dictionary<String, Object> Dyn2Dict(dynamic dynObj) { var dictionary = new Dictionary<string, object>(); foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(dynObj)) { object obj = propertyDescriptor.GetValue(dynObj); dictionary.Add(propertyDescriptor.Name, obj); } return dictionary; }

Parse json string using JSON.NET

You can use .NET 4’s dynamic type and built-in JavaScriptSerializer to do that. Something like this, maybe: string json = “{\”items\”:[{\”Name\”:\”AAA\”,\”Age\”:\”22\”,\”Job\”:\”PPP\”},{\”Name\”:\”BBB\”,\”Age\”:\”25\”,\”Job\”:\”QQQ\”},{\”Name\”:\”CCC\”,\”Age\”:\”38\”,\”Job\”:\”RRR\”}]}”; var jss = new JavaScriptSerializer(); dynamic data = jss.Deserialize<dynamic>(json); StringBuilder sb = new StringBuilder(); sb.Append(“<table>\n <thead>\n <tr>\n”); // Build the header based on the keys in the // first data item. foreach (string key … Read more

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

foreach (var data in dynObj.quizlist) { foreach (var data1 in data.QUIZ.QPROP) { Response.Write(“Name” + “:” + data1.name + “<br>”); Response.Write(“Intro” + “:” + data1.intro + “<br>”); Response.Write(“Timeopen” + “:” + data1.timeopen + “<br>”); Response.Write(“Timeclose” + “:” + data1.timeclose + “<br>”); Response.Write(“Timelimit” + “:” + data1.timelimit + “<br>”); Response.Write(“Noofques” + “:” + data1.noofques + “<br>”); foreach … Read more

Json.NET serializing float/double with minimal decimal places, i.e. no redundant “.0”?

As an alternative answer to question 2 (assuming you don’t want to go through the hassle of compiling your own custom version of the Json.NET source) you can create your own custom JsonConverter class to handle decimal, float, and double values. Here’s the version I’m using: class DecimalJsonConverter : JsonConverter { public DecimalJsonConverter() { } … Read more

Deserialize JSON to 2 different models

First off, your models are slightly incorrect. The name properties need to be strings, instead of integers: class Guardian { [JsonProperty(PropertyName = “guardian_id”)] public int ID { get; set; } [JsonProperty(PropertyName = “guardian_name”)] public string Name { get; set; } // <– This } class Patient { [JsonProperty(PropertyName = “patient_id”)] public int ID { get; … Read more

Add JObject to JObject

You are getting this error because you are trying to construct a JObject with a string (which gets converted into a JValue). A JObject cannot directly contain a JValue, nor another JObject, for that matter; it can only contain JProperties (which can, in turn, contain other JObjects, JArrays or JValues). To make it work, change … Read more