Dump() object to JSON pretty-print string
Dump() object to JSON pretty-print string
Ok, I am having a bit of a problem with this, and I would rather not build my own code if there is an applicable one with permissive license..
I need a way to dump instance of object, any object, into human readable JSON string. Our plan was to use ServiceStack.Text but that piece of software has a restrictive license in v3, and we are not building a FOSS. I also have zero understanding from mgmt about buying commercial license for ServiceStack v4 just to dump objects. So we need something along the lines of MIT licensing.
Internal JSON serializer in WCF seems to only work with DataContract adorned objects.
Any idea if something like that is available?
Perfect... Thanks. We can use 3rd party, as long as the license is permissive for commercial use.
– mmix
Mar 20 '15 at 10:01
Ok, works like a charm. Can you post an answer so that I can accept it?
– mmix
Mar 20 '15 at 10:58
2 Answers
2
Use JSON.Net to convert an object to a JSON String.
string json = JsonConvert.SerializeObject(objectToSerialize);
I also do the following to Format the JSON nicely into a readable file (instead of all just one line)
JToken jt = JToken.Parse(json);
string formattedJson = jt.ToString();
won't I get the same thing with
JsonConvert.SerializeObject(instance, Formatting.Indented);
?– mmix
Mar 20 '15 at 12:21
JsonConvert.SerializeObject(instance, Formatting.Indented);
Maybe, but thats how my google-fu told me :P
– Alex Anderson
Mar 20 '15 at 12:29
Using Newtonsoft.Json also we can achieve the same with
string formattedJson = JsonConvert.SerializeObject(data, Formatting.Indented);
Console.WriteLine(formattedJson);
string formattedJson = JsonConvert.SerializeObject(data, Formatting.Indented);
Console.WriteLine(formattedJson);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Use JSON.NET ? if you can use 3rd party DLLs that is.
– Alex Anderson
Mar 20 '15 at 9:57