0

I want to deserialize a JSON string to a dynamic object in Silverlight using the Newtonsoft.JSON library.

The JSON string is defined as follows:

{"id":42,"longName":"Doe, John","userName":"JD1","domainName":"COMPANY","sid":"A-1-2-34-5678901234-5678901234-5678901234"}

Everything I tried did not work. First attempt was to simply use JObject.Parse as it is mentioned here:

dynamic person = JObject.Parse(myJsonString);
var personId = person.id;

Line 2 crashes, because 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'id', although the debugger shows that my JSON string has been deserialized just fine.

Second approach using JsonConverter.DeserializeObject as proposed here or here:

dynamic person = JsonConvert.DeserializeObject<dynamic>(myJsonString);
var personId = person.id;

I am going to repeat myself but line 2 crashes, because 'Newtonsoft.Json.Linq.JObject' does not contain a definition for 'id', although the debugger shows that my JSON string has been deserialized just fine.

Final approach: Define my own derivate of DynamicObject using a dictionary to internally manage the properties values as outlined in MSDN together with the JsonConvert.DeserializeAnonymousType method:

dynamic person = new DObject();
JsonConvert.DeserializeAnonymousType(result, person);
var id = person.id;

This again fails because my dynamic object does not get populated.

So how do I actually deserialize a JSON string to a dynamic object in Silverlight?

Community
  • 1
  • 1
Spontifixus
  • 6,570
  • 9
  • 45
  • 63
  • can you show us the code behind **DObject** class? – Nikola.Lukovic Jan 08 '15 at 12:07
  • @Nikola.Lukovic It is an exact copy of the `DynamicDictionary` class as shown in the example code in the [MSDN article](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject%28v=vs.110%29.aspx) I linked in the question. – Spontifixus Jan 08 '15 at 13:03

0 Answers0