Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate JSON string from dynamic ExpandoObject

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?

like image 277
Wyck Avatar asked Jun 13 '19 20:06

Wyck


2 Answers

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.

like image 88
carlos chourio Avatar answered Nov 01 '22 22:11

carlos chourio


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.

like image 40
Glenn Ferrie Avatar answered Nov 01 '22 20:11

Glenn Ferrie