w00
w00

Reputation: 26762

Turn a JSON string into a dynamic object

I'm trying to create a dynamic object from a JSON string in C#. But i can't get it done.

Normally i would get a JSON string through a web service call but in this case I simply created a simple class which I turn into a JSON string. Then I try to turn it back into a dynamic object with the exact same structure as if it was an instance of the Entity class. But that's where I'm having trouble.

This is the class that i turn into a JSON string:

public class Entity
{
    public String Name = "Wut";
    public String[] Scores = {"aaa", "bbb", "ccc"};
}

Then in somewhere in my code i do this:

var ent = new Entity();

// The Serialize returns this:
// "{\"Name\":\"Wut\",\"Scores\":[\"aaa\",\"bbb\",\"ccc\"]}"
var json = new JavaScriptSerializer().Serialize(ent);

dynamic dynamicObject1 = new JavaScriptSerializer().DeserializeObject(json);
dynamic dynamicObject2 = Json.Decode(json);

When I debug this code then i see that the first dynamicObject1 returns a Dictionary. Not really what I'm after.

The second dynamicObject2 looks more like the Entity object. It has a property called Name with a value. It also has a dynamic array called Scores, but for some reason that list turns out to be empty...


Screenshot of empty Scores property in dynamic object:

Dynamic object


So I'm not having any luck so far trying to cast a JSON string to a dynamic object. Anyone any idea how I could get this done?

Upvotes: 0

Views: 3476

Answers (2)

MiguelSlv
MiguelSlv

Reputation: 15113

Using Json.Net but deserializing into a ExpandableOBject, a type that is native to C#:

 dynamic obj= JsonConvert.DeserializeObject<ExpandoObject>(yourjson);

If the target type is not specified then it will be convert to JObject type instead. Json object has json types attached to every node that can cause problems when converting the object into other dynamic type like mongo bson.

Upvotes: 0

L.B
L.B

Reputation: 116098

Using Json.Net

dynamic dynamicObject1  = JsonConvert.DeserializeObject(json);
Console.WriteLine(dynamicObject1.Name);

Upvotes: 2

Related Questions