I am using the Newtonsoft.Json assembly to de-serialize a Json string into a dynamic object (ExpandoObject). The problem I am having is the int value is always returned as an Int64 where I am expecting an Int32. The code can be seen below.
namespace Serialization
{
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public static class JsonSerializer
{
#region Public Methods
public static string Serialize(dynamic obj)
{
return JsonConvert.SerializeObject(obj);
}
public static dynamic Deserialize(string s)
{
var obj = JsonConvert.DeserializeObject(s);
return obj is string ? obj as string : Deserialize((JToken)obj);
}
#endregion
#region Methods
private static dynamic Deserialize(JToken token)
{
// FROM : http://blog.petegoo.com/archive/2009/10/27/using-json.net-to-eval-json-into-a-dynamic-variable-in.aspx
// Ideally in the future Json.Net will support dynamic and this can be eliminated.
if (token is JValue) return ((JValue)token).Value;
if (token is JObject)
{
var expando = new ExpandoObject();
(from childToken in token
where childToken is JProperty
select childToken as JProperty).ToList().
ForEach(property => ((IDictionary<string, object>)expando).Add(property.Name, Deserialize(property.Value)));
return expando;
}
if (token is JArray)
{
var items = new List<object>();
foreach (var arrayItem in ((JArray)token)) items.Add(Deserialize(arrayItem));
return items;
}
throw new ArgumentException(string.Format("Unknown token type '{0}'", token.GetType()), "token");
}
#endregion
}
}
Normally I wouldn't notice this but this particular int is being used in reflection for some type checking and it fails miserably. Any ideas why this is happening would be greatly appreciated.