I am using C# and trying to generate a JSON string from a dynamic object.
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = System.Web.Helpers.Json.Encode(reply);
System.Console.WriteLine(json);
(Note, the above requires a reference to the System.Web.Helpers assembly.)
I was hoping for this to output the string:
{"name":"John","wins":42}
But it actually outputs:
[{"Key":"name","Value":"John"},{"Key":"wins","Value":42}]
What do I need to change to get the output I was hoping for?
Just download the Newtonsoft.Json Nuget package.
That's the preferred way of working with json in c#. Your code using Newtonsoft would be:
dynamic reply = new System.Dynamic.ExpandoObject();
reply.name = "John";
reply.wins = 42;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
System.Console.WriteLine(json);
EDIT:
I just want to explain better why you're getting that result when you're using the System.Web.Helpers.Json.Encode
method.
An ExpandoObject is an object which fields are defined at runtime, different than a regular object which fields/properties/methods .. are defined at compile-time. To be able to define them at run-time the expando object internally holds a dictionary, which is a collection of key-value pairs.
I don't know how that helper works but it's probably just a simple serializer and that's why it's serializing to an array of key- value pairs instead of the actual object you're expecting. The library Newtonsoft.Json is almost an standard for c# projects and obviously is aware of how the Expando Object works internally.
Using the Newtonsoft.Json
tools:
using Newtonsoft.Json;
/// skip a bunch of other implementation details.
var json = Newtonsoft.Json.JsonConvert.SerializeObject(reply);
That's how I do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With