【问题标题】:javascript custom converter deserialize json arrayjavascript自定义转换器反序列化json数组
【发布时间】:2013-02-06 20:46:40
【问题描述】:

我有一个包含 long 数组的对象模型,我正在反序列化一个 json 字符串,该字符串包含一个使用自定义 javascript 转换器和 javascript 序列化程序类的数组。

我认为这会起作用,但它没有:

List<long> TheList = new List<long>;

if (dictionary.ContainsKey("TheArray") && dictionary["TheArray"] != null)
{
    TheList = serializer.ConvertToType<List<long>>(dictionary["TheArray"]); //bug
    TheObject.TheObjectList = (from s in TheList 
                               select Convert.ToInt64(s)).ToList<long>();
}

错误在TheList = serializer.ConvertToType...这一行,错误信息是:

无法将“System.String”类型的对象转换为类型 'System.Collections.Generic.List`1[System.Int64]'

我也试过这个:

var TheStringArray = serializer.ConvertToType<string>(dictionary["TheArray"]);

TheObject.TheObjectList = (from s in TheStringArray.Split(',') 
                           select Convert.ToInt64(s)).ToList<long>();

但随后我收到此错误消息:

数组的反序列化不支持类型“System.String”。

我错过了什么?

谢谢。

【问题讨论】:

  • 数组(字符串?)中的所有值都是有效的 Int64 值吗?
  • 是的,它们都是 javascript int 值。作为预防措施,我实际上还在下一行将值解析为 Int64。
  • 请向我们展示您的 JSON
  • json是一个字典,里面有一个数字数组,都是经典的,没什么花哨的。

标签: c# json


【解决方案1】:

数组对JavaScriptConverter 可见为ArrayList,您可以像这样处理反序列化:

List<long> theArray = null;

if (dictionary.ContainsKey("TheArray") && dictionary["TheArray"] is ArrayList)
{
    theArray = new List<long>();
    ArrayList serializedTheArray = (ArrayList)dictionary["TheArray"];
    foreach (object serializedTheArrayItem in serializedTheArray)
    {
        if (serializedTheArrayItem is Int64)
            theArray.Add((long)serializedTheArrayItem);
    }
}

这将检查所有类型,以防 JSON 中出现意外情况。当然,它假设 JSON 中的 TheArray 属性实际上包含一个数组,而不是表示数组的内部 JSON 字符串(错误消息可能表明这种问题)。

【讨论】:

  • 好的,我可以让您的 serializedTheArray 包含该数组。现在我正在用 linq 编写第二行,就像我在问题中而不是 foreach 循环中一样。
猜你喜欢
  • 1970-01-01
  • 2011-04-12
  • 1970-01-01
  • 1970-01-01
  • 2015-02-17
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
相关资源
最近更新 更多