The Problem
Hi all,
I'm trying to deserialize Json-strings with known (static) and unknown (dynamic) properties. For this I'm using Json.NET and System.Dynamic.DynamicObject
.
In my first attempt, I was using Json.NET-specific Serialization Attributes to configure the (de-)serializer. However the dynamic properties in the Json-string are not deserialized in that case. But when I switch to native .NET attributes ([DataContract]
and [DataMember]
), the dynamic properties are deserialized and I can access them in the created dynamic object.
Is this behavior intended? Am I missing any configuration with the Json.NET attributes to get the same deserialization behavior?
Any clarification would be highly appreciated!
The Details
Here I'm providing the details of my implementation (using Json.NET attributes). I'm using .NET 4.5 and Json.NET 6.0.2
Because I have multiple message types with static and dynamic properties, I introduced a base class, which implements the dynamic handling property:
[JsonObject]
internal abstract class DynamicMessage : DynamicObject
{
[JsonProperty]
public Dictionary<string, object> dynamicProperties = new Dictionary<string, object();
public override bool TryGetMember(GetMemberBinder binder, out object result) {...}
public override bool TrySetMember(SetMemberBinder binder, object value) {...}
}
The concrete subclass is looks like this:
[JsonObject]
internal class ItemMessage : DynamicMessage
{
[JsonPropertyAttribute(PropertyName = "id")]
internal long Id;
[JsonPropertyAttribute(PropertyName = "parent_item");
internal long ParentItemId;
...
}
And I tried the deserialize the following string like this:
jsonString = @{'id':1,
'parent_item':5,
'my_dynamic_property_1' : 1337,
'my_dynamic_property_2' : 'my_dynamic_property_2'}
JsonSerializer serializer = new JsonSerializer();
dynamic itemMessage = serializer.Deserialize<ItemMessage>(new JsonTextReader(jsonString));
As I pointed out in the beginning, if I'm using the attributes [JsonObject]
and [JsonProperty]
all static properties are correctly deserialized and bound to the POCO properties, but I'm lacking the dynamic properties my_dynamic_property_1
and my_dynamic_property_2
.
When I change to [DataContract]
(for [JsonObject]
) and [DataMember]
(for [JsonProperty]
) also the dynamic properties in the Json will be deserialized and I can call
itemMessage.my_dynamic_property_1; //=1337
itemMessage.my_dynamic_property_2; //="my_dynamic_property_2"