JsonConvert.DeserializeObject w/ DynamicObject and TypeCreationConverter

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;

					
public class Program
{
	public static void Main()
	{
		const string JSON = @"{'Name': 'my first story', 'ToldByUserId': 255 }";
		
		var stroy = JsonConvert.DeserializeObject<EntityBase>(JSON, new StoryCreator());

	}
}

// this is not the actual type but a mock to test the behavior with
public class EntityBase : DynamicObject
{
	public string EntityName { get; private set; }
	
	private readonly Dictionary<string, object> values = new Dictionary<string, object>();
	
	public EntityBase(string entityName)
	{
		this.EntityName = entityName;
	}
	
	public virtual object this[string fieldname]
	{
		get
		{
			if (this.values.ContainsKey(fieldname))
				return this.values[fieldname];
			
			return null;
		}
		
		set
		{
			if (this.values.ContainsKey(fieldname))
				this.values[fieldname] = value;
			else
				this.values.Add(fieldname, value);
			
		}
	}
	
	public override IEnumerable<string> GetDynamicMemberNames()
	{
		return this.values.Keys.ToList();
	}
	
	// If you try to get a value of a property
	// not defined in the class, this method is called.
	public override bool TryGetMember(GetMemberBinder binder, out object result)
	{
		result = this[binder.Name];
		return true;
	}
	
	// If you try to set a value of a property that is
	// not defined in the class, this method is called.
	public override bool TrySetMember(SetMemberBinder binder, object value)
	{
		this[binder.Name] = value;
		return true;
	}
	
}

public class StoryCreator : CustomCreationConverter<EntityBase>
{
	public override EntityBase Create(Type objectType)
	{
		return new EntityBase("Stroy");
	}
}

;