15

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?

1

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I really appreciate your insight about how the Web.Helpers implementation is inferior to the Netwonsoft.Json implementation. I would certainly make a feature request for Web.Helpers that there be a serialization option to treat ExpandoObject in the expected way. The current functionality of Web.Helpers is logical (as you have described), but it's not useful at all for ExpandoObject.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.