Reputation:
I'm trying to convert my dictionary to JSON. I have a client server application set and I'm trying to create an outgoing packet on the server side, but I have the packet data in a dictionary.
My dictionary structure is set up something like this.
"device.name" => "Machine-39FK394S"
"device.username" => "admin"
"device.operating_system" => "Windows 10"
"something.else" => 294
A dot represents another level in JSON, the output in JSON would be like this.
{
"device" : {
"name" : "Machine-39FK394S",
"username" : "admin",
"operating_system" : "Windows 10",
}
"something" : {
"else" : 294,
}
}
What have I tried so far?
public string GetJson()
{
var entries = _packetData.Select(d => string.Format("\"{0}\": [{1}]", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
Although the above method just outputs an empty {}
json string.
Upvotes: 1
Views: 2162
Reputation: 30685
How about something like this, it should work for any number of properties:
var inputDict = new Dictionary<string, object>();
inputDict["device.name"] = "Machine-39FK394S";
inputDict["device.username"] = "admin";
inputDict["device.operating_system"] = "Windows 10";
inputDict["something.else"] = 294;
var outputObject = new Dictionary<string, object>();
foreach (var kvp in inputDict)
{
var currentDict = outputObject;
var depth = 0;
var fields = kvp.Key.Split('.');
foreach (var field in fields)
{
if (++depth == fields.Length)
{
currentDict[field] = kvp.Value;
}
else if (!currentDict.ContainsKey(field))
{
currentDict[field] = new Dictionary<string, object>();
}
currentDict = currentDict[field] as Dictionary<string, object>;
}
}
var json = JsonConvert.SerializeObject(outputObject, Formatting.Indented);
Console.WriteLine("JSON: " + json);
I get the output below:
{
"device": {
"name": "Machine-39FK394S",
"username": "admin",
"operating_system": "Windows 10"
},
"something": {
"else": 294
}
}
This uses Newtonsoft Json.Net, however I do believe it would be hard to compose this JSON without such a library. Json.Net will handle all the conversion of various types of objects to string, plus it will handle escaping JSON delimiters. Writing this type of code yourself will be very nasty. In addition it's highly customizable and will allow datetime formats etc. to be changed.
You might need a little refinement to handle NULLs etc.
If you wish to avoid using Json.Net, you can add a reference to System.Web.Extensions and like so:
using System.Web.Script.Serialization;
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize(outputObject);
Upvotes: 2
Reputation: 23797
You can use Newtonsoft.Json from NuGet to do that. ie:
var data = new
{
device = new
{
name = "Machine-39FK394S",
username = "admin",
operating_system = "Windows 10"
},
something = new {_else=294}
};
var json = JsonConvert.SerializeObject(data, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
Upvotes: 0