开发者

Are there any JSON serializers for C# .Net 4.0+ that serialize JSON to Dictionary<string,dynamic> and dynamic[]

I know you can serialize JSON to Dictionary and object[], but the problem is that it requires you to constantly cast things all over the place:

using System.Web.Script.Serialization;

var json = new JavaScriptSerializer { }.DeserializeObject(@"{array:['item1','item2']}") as Dictionary<string, object>;
var strings = new List<string> { };
if (json != null)
{
    var array = json["array"] as object[];
    if (array != null)
    {
        foreach (var item in array.Select(i=>i as string))
        {
            if (!string.IsNullOrWhiteSpace(item))
            {
                strings.Add(item);
            }
        }
    }
}
return strings.ToArray();

I would much rather do something more like:

开发者_JAVA技巧
try
{
    var json = new JavaScriptSerializer { }.DeserializeDynamic(@"{array:['item1','item2']}") as Dictionary<string, dynamic>;
    var strings = new List<string>{};
    foreach (var item in json["array"])
        strings.Add(item as string);
    return strings.ToArray();
}
catch { return null; }

I have run into problems with object[] and number types, I'm never sure if it's going to be an int, a float, a decimal, or a double etc. I can't sanitize my json data so it reliably is only a double...

Are there any JSON Serializers for .Net 4.0 that output Dictionary and dynamic[]? That just seams like a more natural choice for working with json then Dictionary and object[]...


JSON.NET should handle your needs (with the Json.NET Dynamic Extensions).


Dictionary<string, object> and Dictionary<string, dynamic> are the same types as far runtime is concerned.

For example this works:

var dynDic =new Dictionary<string,object>{ {"test", 1}}
                    as Dictionary<string,dynamic>;
int value = dynDic["test"];

So if your first works:

var json = new JavaScriptSerializer { }
         .DeserializeObject(@"{array:['item1','item2']}") 
         as Dictionary<string, object>;

then so should:

var json = new JavaScriptSerializer { }
         .DeserializeDynamic(@"{array:['item1','item2']}")
         as Dictionary<string, dynamic>;

But then :

foreach (var item in json["array"])
    strings.Add(item as string);

doesn't use dynamic invocation so it compiles that same whether the item var was object or dynamic so if you are having problems my guess is it's in the use of dynamic.

Same rule applies to object[] and dynamic[], they are the same type, you can freely cast between them, when you cast you are just telling the compiler how to use the objects from that array.

dynamic[] dynArr = new object[]{1};

So the answer is that anything that will deserialize to Dictionary<string,object> or object[] can be used as Dictionary<string,dynamic> or dynamic[]

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜