Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a Dictionary<string,string> to an existing JSON.Net's JObject?

Tags:

json.net

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].

like image 439
Mason G. Zhwiti Avatar asked Mar 06 '13 22:03

Mason G. Zhwiti


People also ask

How do you serialize a dictionary to a JSON 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.

How to deserialize string to JSON object in c#?

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.

What is JObject C#?

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.


1 Answers

I believe that you are looking for something like this:

json["dict"] = JObject.FromObject(dict); 
like image 61
Vitaliy Kalinin Avatar answered Oct 26 '22 00:10

Vitaliy Kalinin