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.
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.
Serializing data structures containing only numeric or boolean values is fairly straightforward. If you don't have much to serialize, you can write a method for your specific type.
For a Dictionary<int, List<int>> as you have specified, you can use Linq:
string MyDictionaryToJson(Dictionary<int, List<int>> dict)
{
var entries = dict.Select(d =>
string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
But, if you are serializing several different classes, or more complex data structures, or especially if your data contains string values, you would be better off using a reputable JSON library that already knows how to handle things like escape characters and line breaks. Json.NET is a popular option.
C# JSON System.Text.Json - How to extract an object from a dictionary or List<Dictionary<string, object>>(json) ?
How to convert JSON to Dictionary
How to use Json Data as dictionary key and find the value?
Need some help with Dictionaries and JsonSerializer
Videos
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,
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!
Json.NET does this...
Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = JsonConvert.SerializeObject(values);
// {
// "key1": "value1",
// "key2": "value2"
// }
More examples: Serializing Collections with Json.NET
In .NET 5 and later, you can simply write:
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
Dictionary<string, string> values = new();
values.Add("key1", "value1");
values.Add("key2", "value2");
string json = System.Text.Json.JsonSerializer.Serialize(values);
Console.WriteLine(json);
}
}
to get {"key1":"value1","key2":"value2"}.
No external dependency is needed.
How to convert list of dictionary to list of json objects?
input = [{'a':'b'},{'c':'d'}]
expectedOutput = [{"a":"b"},{"c":"d"}]
I tried following but couldn't get expected result
-
json.dumps(input)gives string'[{"a":"b"},{"c":"d"}]' -
Iterate through dictionary and convert each dict to json object gives
['{"a":"b"}','{"c":"d"}']
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?
json.dumps() converts a dictionary to str object, not a json(dict) object! So you have to load your str into a dict to use it by using json.loads() method
See json.dumps() as a save method and json.loads() as a retrieve method.
This is the code sample which might help you understand it more:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
json.dumps() returns the JSON string representation of the python dict. See the docs
You can't do r['rating'] because r is a string, not a dict anymore
Perhaps you meant something like
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))