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?