是否有适用于 C# .Net 4.0+ 的 JSON 序列化器将 JSON 序列化为 Dictionary和动态[]

发布于 2024-12-04 02:50:20 字数 1187 浏览 0 评论 0原文

我知道你可以将 JSON 序列化为 Dictionary 和 object[],但问题是它需要你不断地将东西投射到各处:

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();

我宁愿做一些更像这样的事情:

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; }

我遇到了 object[] 和 number 的问题类型,我不确定它是否会是 int、float、decimal 或 double 等。我无法清理我的 json 数据,因此它可靠地只是一个 double...

是否有任何 JSON 序列化器.Net 4.0 输出字典和动态[]?这似乎是使用 json 的更自然的选择,然后是 Dictionary 和 object[]...

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:

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[]...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

鱼忆七猫命九 2024-12-11 02:50:20

JSON.NET 应该可以满足您的需求(使用 Json.NET 动态扩展)。

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

淡淡離愁欲言轉身 2024-12-11 02:50:20

DictionaryDictionary 就运行时而言是相同的类型。

例如,这有效:

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

因此,如果您的第一个有效:

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

那么应该:

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

但是 then :

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

不使用动态调用,因此无论项目 varobject 还是,它都会编译相同的内容dynamic 因此,如果您遇到问题,我猜测是在使用 dynamic 时出现的问题。

同样的规则适用于 object[]dynamic[],它们是相同的类型,你可以在它们之间自由转换,当你转换时,你只是告诉编译器如何使用该数组中的对象

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

所以答案是任何反序列化为 Dictionaryobject[] 的东西都可以用作 Dictionary > 或动态[]

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[]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文