I've got a JObject (using JSON.Net) that I created by parsing some JSON text. I'm directly manipulating, adding keys at the top level of this JObject. I have no problems when the value I'm adding is a string:
json["newkey"] = "New Value"; // works
But I'll be damned if I can figure out how to add a Dictionary, e.g.:
Dictionary<string,string> dict = new Dictionary<string,string>(); dict["one"] = "1"; dict["two"] = "2"; json["dict"] = dict; // fails
I've done quite a bit of googling and reading the JSON.Net docs, but everything seems oriented towards reason JSON text into a JObject, or writing .NET objects as JSON text using serialization. Or using some fancy LINQ statements to do all kinds of things with complex objects...
I've tried these and none have worked:
json["dict"] = new JObject(dict); json["dict"] = new JObject((Dictionary<string,string>)dict); json["dict"] = new JArray(dict); // desperation sets in :) json["dict"] = (JObject)dict; // please dear god let this work
Most of the latest errors I encounter are:
Could not determine JSON object type for type System.Collections.Generic.KeyValuePair`2[System.String,System.String].
Simple One-Line Answer. This code will convert any Dictionary<Key,Value> to Dictionary<string,string> and then serialize it as a JSON string: var json = new JavaScriptSerializer(). Serialize(yourDictionary.
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft.
I believe that you are looking for something like this:
json["dict"] = JObject.FromObject(dict);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With