This answer mentions Json.NET but stops short of telling you how you can use Json.NET to serialize a dictionary:

return JsonConvert.SerializeObject( myDictionary );

As opposed to JavaScriptSerializer, myDictionary does not have to be a dictionary of type <string, string> for JsonConvert to work.

Answer from Big McLargeHuge on Stack Overflow
🌐
Medium
akarshseggemu.medium.com › objective-c-how-to-convert-a-dictionary-to-json-string-752e410fead1
Objective-C: How to convert a dictionary to JSON string? | by Akarsh Seggemu, M.Sc. | Medium
June 25, 2022 - The dictionary is converted into a NSMutableDictionary object into a JSON object and stored in data. The options parameter NSJSONWritingPrettyPrinted makes the JSONS object more readable. The jsonString stores the converted data using UTF-8 code units encoding. ... I hope my article helps you understand how to convert a dictionary to JSON string in Objective-C.
Discussions

C# JSON System.Text.Json - How to extract an object from a dictionary or List<Dictionary<string, object>>(json) ?
Hello, I am trying to populate embeds with data taken from a JSON file, however I am not familiar with that format. The JSON file follows this format (it's a single array of objects which all contain the same fields): [{ "Id":… More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
March 18, 2023
How to convert JSON to Dictionary
Hi Team, How to convert JSON to Dictionary? Inside the JObject I can see multiple Object. Sample JSON Object: { “Name”: “ABC”, “Age”: 30, “Location”: { “City”: “Bangalore”, “Country”: “India” }, “Skills”: { “Sport”: “Cricket” “Technology”: ... More on forum.uipath.com
🌐 forum.uipath.com
1
0
September 24, 2024
How to use Json Data as dictionary key and find the value?
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support. Download Microsoft Edge More info about Internet Explorer and Microsoft Edge ... Hello: I have the following Json data stored into one dictionary: (newtonsoft.json) public class JsonKey ... More on learn.microsoft.com
🌐 learn.microsoft.com
1
0
January 24, 2023
Need some help with Dictionaries and JsonSerializer
JSON does not include type information, and you’ve specified object which can literally be anything, so serializers do the best they can - it deserializes as JsonElement (System.Text.Json) or JToken (Newtonsoft) You’re then soft-casting to the type that you want, but it’s not that type, so you get null You can either make a proper class instead of using a dictionary (where the key you want is a named property with the correct type), or you can re-serialize the value of key you want and then re-deserialize as the type you want. More on reddit.com
🌐 r/csharp
11
2
September 22, 2023
🌐
Reddit
reddit.com › r/csharp › json to c# dictionary questions
r/csharp on Reddit: JSON to C# Dictionary questions
October 29, 2019 -

I don't quite understand a couple things. I found a bunch of code on how to deserialize JSON to a C# dictionary, but nothing that quite exactly matched what I wanted to do.

So I have some JSON that looks like this:

{
  "Authorized" : [
  {"Key" : "John", "Authorized_Buildings" : ["Building 1", "Building 3", "Building 5"]},
  {"Key" : "Bob", "Authorized_Buildings" : ["Building 1", "Building 5"]},
  {"Key" : "Joe", "Authorized _Buildings" : ["Building 2", "Building 3"]}
  ], 

  "Building Info" : [
{"Key" : "One", "Floors" : 4, "Exits" : "Multiple"}, 
{"Key" : "Two", "Floors" : 3, "Exits" : "One"}
 ]
}

I would like to deserialize each of these JSON "Objects" into two different Dictionaries<string, Authorized> and Dictionary <string, buildingInfo>.

My issues are how do I only send the authorized objects to that class and the Building Info objects to that Dictionary? createAuthorizedDictionaryFromJSON(jo["Authorized"].ToString());

Second, how do I force the dictionary to use what I want as the key to the custom object? So for Building Info, I want two properties in the class. A floor int and an Exits string.

I appreciate any help.

Cheers,

Top answer
1 of 4
2
Default serialization will take a standard json object into a dictionary Ex: this will serialize properly public class DataModel { public Dictionary Values { get; set; } } { "values": { "name": "bob", "skill": "none" } } Tldr; although a dictionary is a collection type in .net, having unique keys makes it suitable as a handler for a loosely coupled JSON objects, so deserialization allows that to happen
2 of 4
1
Not the most elegant solution, I'll grant you... but your model can be serialized like this: // usings/references using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; // class models [DataContract] class MyObject { [DataMember] public List Authorized { get; set; } [DataMember(Name = "Building Info")] public List BuildingInfo { get; set; } } [DataContract] class Authorized { [DataMember] public string Key { get; set; } [DataMember(Name = "Authorized_Buildings")] public List AuthorizedBuildings { get; set; } } [DataContract] class BuildingInfo { [DataMember] public string Key { get; set; } [DataMember] public int Floors { get; set; } [DataMember] public string Exits { get; set; } } // implementation code string json = "...your json..."; MyObject obj = new MyObject(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json))) { var serializer = new DataContractJsonSerializer(obj.GetType()); obj = serializer.ReadObject(stream) as MyObject; stream.Close(); } // "obj" now holds the model data deserialized. // All the List types in the model classes could be arrays... the serializer won't care. Note that you have a typo in Joe's "Authorized_Buildings"... there's a space in the name. The MyObject class is just a placeholder because your json doesn't specify a contract name. There are many other ways to serialize/deserialize json data. This is just one.
🌐
Newtonsoft
newtonsoft.com › json › help › html › serializedictionary.htm
Serialize a Dictionary
This sample serializes a dictionary to JSON. ... Dictionary<string, int> points = new Dictionary<string, int> { { "James", 9001 }, { "Jo", 3474 }, { "Jess", 11926 } }; string json = JsonConvert.SerializeObject(points, Formatting.Indented); Console.WriteLine(json); // { // "James": 9001, // "Jo": 3474, // "Jess": 11926 // }
🌐
Code Maze
code-maze.com › home › how to serialize a dictionary to json in c#
How to Serialize a Dictionary to JSON in C# - Code Maze
May 17, 2023 - We just need to create a custom converter and add it to our serializer options declaration: public sealed class SystemJsonCustomerInvoiceConverter : JsonConverter<Dictionary<Customer, List<Invoice>>> { public override void Write(Utf8JsonWriter writer, Dictionary<Customer, List<Invoice>> value, JsonSerializerOptions options) { writer.WriteStartObject(); foreach (var (customer, invoices) in value) { writer.WritePropertyName($"Customer-{customer.CustomerId:N}"); writer.WriteStartObject(); WriteCustomerProperties(writer, customer); WriteInvoices(writer, invoices); writer.WriteEndObject(); } writer.WriteEndObject(); } // Omitted for brevity }
🌐
JD Bots
jd-bots.com › 2023 › 02 › 17 › convert-dictionary-to-json-object-in-c-example-code
Convert Dictionary to JSON Object in .NET C# | Example Code
February 17, 2023 - Learn how to convert a dictionary to a JSON object in .NET C# using the Newtonsoft.Json NuGet package. Follow our example code and get started with JSON serialization.
Find elsewhere
🌐
Microsoft
social.msdn.microsoft.com › Forums › vstudio › en-US › 31df8ccb-b812-4914-b9a4-3116c65c2cc8 › how-to-convert-dictionary-to-json-using-three-arguments
How to Convert dictionary to json using three arguments | Microsoft Learn
January 12, 2018 - JSON tends to use camel casing. Other serializers allow you to change this but I don't think JavaScriptSerializer does. If you stick with this serializer then you'll need to adjust the members to serialize what you want. ... Here's an example that uses the dictionary object.
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1163907 › how-to-use-json-data-as-dictionary-key-and-find-th
How to use Json Data as dictionary key and find the value? - Microsoft Q&A
January 24, 2023 - It is designed to generate a hash code quickly for use in hash-based data structures like dictionaries and sets, and it is based on the current state of the runtime environment. In your case, you can use the JsonConvert.SerializeObject method to serialize the JsonKey object into a string, which can be used as the dictionary key.
🌐
Automation Anywhere
docs.automationanywhere.com › bundle › enterprise-v2019 › page › convert-dictionary-to-json.html
Convert Dictionary to JSON
This action enables you to convert the content of a dictionary variable to JSON format, representing all key-value pairs.
🌐
Reddit
reddit.com › r/csharp › need some help with dictionaries and jsonserializer
r/csharp on Reddit: Need some help with Dictionaries and JsonSerializer
September 22, 2023 -

So I have a Dictionary<string,object>, one of the values is an array of Godot's Button class. I then serialize and deserialize it but when I try to access the array nested within the dictionary, I get a null reference.

Dictionary<string,object> thisDict = new()
{
    {"someKey", someValue},
    {"someKey", someValue},
    {"arrayKey", Array.Empty<Button>()}
};

string thisString = JsonSerializer.Serialize(thisDict);

Dictionary<string,object> anotherDict = JsonSerializer.Deserialize<Dictionar<string,object>>(thisString);
Button[] myResult = anotherDict["arrayKey"] as Button[];

GD.Print(myResult);    //null
GD.Print(anotherDict["arrayKey"]);    //[]
GD.Print(anotherDict["arrayKey"].GetType());    //System.Text.Json.JsonElement
GD.Print(anotherDict);    //System.Collections.Generic.Dictionary`2[System.String,System.Object]

So the Dictionary works and the values are shown as correct in the console (others too, I tested them - strings, integers etc all correct), but of the type System.Text.Json.JsonElement and therefor I can't cast them and they become null.

Am I casting it wrong? Couldn't find a matching answer on Google for how to get from JsonElement to any native C# type. Or is there something wrong with my Serialization?

Thanks in advance!

🌐
KDnuggets
kdnuggets.com › convert-python-dict-to-json-a-tutorial-for-beginners
Convert Python Dict to JSON: A Tutorial for Beginners - KDnuggets
In practice, however, you’ll need to convert not a single dictionary but a collection such as a list of dictionaries. So let’s choose such an example. Say we have books, a list of dictionaries, where each dictionary holds information on a book. So each book record is in a Python dictionary with the following keys: title, author, publication_year, and genre. When calling json.dumps(), we set the optional indent parameter—the indentation in the JSON string as it helps improve readability (yes, pretty printing json we are ??):
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 1337435 › need-help-to-write-read-dictionary(string-object)
Need help to write/read dictionary<string,object> to/from the file location. - Microsoft Q&A
July 26, 2023 - Both methods will write the content to the file and overwrite the file if it already exists. using Newtonsoft.Json; using System.IO; string libraryPath = UsersSettingsFileName; // file path Dictionary<string, object> _globalsetting = new Dictionary<string, object>(); _globalsetting[globalSetting.Key] = globalSetting.Data; // Add data to the dictionary string content = JsonConvert.SerializeObject(_globalsetting); // Serialize the dictionary to JSON // Write the JSON content to the file (overwriting the file if it already exists) File.WriteAllText(libraryPath, content);
🌐
Reddit
reddit.com › r/unity3d › string dictionary to json?
r/Unity3D on Reddit: string Dictionary to JSON?
March 22, 2023 -

I'm trying to figure out the easiest way to get a Dictionary<string, string> to a JSON array string format, so that for example:

 Dictionary<string, string> myDict = new Dictionary<string, string>()
 myDict.Add("name", "john");
 myDict.Add("age", "21");

is converted to

  [ 
      "name" : "john",
      "age" :  "21"
  ]

and so on.

I can't seem to fine a NewtonSoft.JSON (included in Unity) call that will do that.

Is it easier to just iterate over the dictionary and build that string manually?

🌐
UiPath Community
forum.uipath.com › help
How to load json file into dictionary - Help - UiPath Community Forum
March 4, 2019 - Hi Everyone. Can anyone please tell me how to Load a JSON file into a dictionary. I have done up to deserialize JSON after that I took For each activity from there onwards I was Stuck. Thanks in advance Regards, CRN…