If I want to deserialize to an ExpandoObject using Json.NET, I can do the following:
var obj2 = JsonConvert.DeserializeObject<ExpandoObject>(serializedData, new ExpandoObjectConverter());
But because I need to get back an object with a certain interface out of deserialization, I need to use a DynamicObject instead of ExpandoObject:
public interface ISomeInterface
{
public string InterfaceMember { get; set; }
}
public class SomeClass: ISomeInterface
{
public int X { get; set; }
public string InterfaceMember { get; set; }
}
public class SomeClass2 : DynamicObject, ISomeInterface
{
public string InterfaceMember { get; set; }
}
But when I do the following, I get an error:
var obj = new SomeClass
{
InterfaceMember = "xyz",
X = 3
};
string serializedData = JsonConvert.SerializeObject(obj);
SomeClass2 obj2 = JsonConvert.DeserializeObject<SomeClass2>(serializedData, new ExpandoObjectConverter());
And the error is:
'SomeClass2' does not contain a definition for 'X'
How can I make it work for a DynamicObject?
NOTE: I am providing the concrete class SomeClass here just for the sake of the example. At runtime, it can actually be any type implementing ISomeInterface. So, I cannot deserialize directly to SomeClass. My actual goal is to deserialize to ISomeInterface.
DynamicObject. You can just use the overload that takes aTypeat runtime (providing the actual type, and casting toISomeInterfaceafterwards).SomeClass2is not valid to ask about property X ... but fordynamicit is valid