Does anyone know how to serialize object as the follow code using Json.NET?
class Program
{
static void Main(string[] args)
{
var dic = new Dictionary<string, object>();
dic.Add("key", true);
dic.Add("create", false);
dic.Add("title", "Name");
dic.Add("option2", @"function(value){ return value; }");
dic.Add("fields", new Dictionary<string, object>
{
{"Id", new Dictionary<string, object>
{
{"title", "This is id"}
}
}
});
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(dic, Formatting.Indented));
}
}
Result output is a json string:
{
"key": true,
"create": false,
"title": "Name",
"option2": "function(value){ return value; }",
"fields": {
"Id": {
"title": "This is id"
}
}
}
But I expect it as the following code (it looks like javascript hash):
{
key: true,
create: false,
title: "Name",
option2: function(value){ return value; },
fields: {
Id: {
title: "This is id"
}
}
}
The below code will show the output as I expect. But I need a different solution. Please help me. Thank you
private static void SerializeObject(IDictionary<string, object> dic)
{
Console.WriteLine("{");
foreach (var key in dic.Keys)
{
var value = dic[key];
if (value is JsFunction) // just a wrapper class of string
{
Console.WriteLine("{0}: {1}", key, value);
}
else if (value is IDictionary<string, object>)
{
Console.WriteLine("{0}:", key);
SerializeObject(value as IDictionary<string, object>);
}
else
{
Console.WriteLine("{0}: {1}", key, JsonConvert.SerializeObject(dic[key]));
}
}
Console.WriteLine("}");
}