0

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

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

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”。

我错过了什么?

谢谢。

4

1 回答 1

1

Array is visible to JavaScriptConverter as ArrayList, you may approach the deserialization like this:

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

This will do all types checking in case there is somethign unexpected in the JSON. Of course it assumes that TheArray property in JSON in fact contains an Array, not inner JSON string which represents Array (the error message might suggest this kind of issue).

于 2013-02-06T12:46:40.617 回答