Generate JSON string from dynamic ExpandoObject
Asked Answered
J

2

14

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?

Jeanicejeanie answered 13/6, 2019 at 20:47 Comment(1)
You should use Newtonsoft.Json. Nuget Link: nuget.org/packages/Newtonsoft.JsonAmabelle
M
20

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.

Mopey answered 13/6, 2019 at 20:57 Comment(1)
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.Jeanicejeanie
A
3

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.

Amabelle answered 13/6, 2019 at 20:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.