JavaScriptSerializer从JavaScript字符串或数组反序列化为.NET string []

时间:2011-11-16 20:17:55

标签: c# asp.net .net json

JavaScriptSerializer(我现在不想使用其他库),我可以做这样的事情吗?

class Model 
{
    string[] Values { get; set; }
}

// using the serializer

JavaScriptSerializer serializer = new JavaScriptSerializer();

// this works
Model workingModel = serializer.Deserialize<Model>("{ Values : ['1234', '2346'] }");

// this works
Model wontWorkModel = serializer.Deserialize<Model>("{ Values : 'test' }");

我希望wontWorkModel.Values成为包含1个项目的数组 - test

这是否可以使用我指定的JSON?

修改

我能够使用TypeConverter并将其插入string[]类型中来解决这个问题,但它看起来非常h​​ackish(并且我可以在.NET中做到这一点很可怕)。

2 个答案:

答案 0 :(得分:1)

一种选择是创建一个JavascriptConverter:

public class ModelConverter   : JavaScriptConverter
    {
        public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
        {
            if (dictionary == null)
                throw new ArgumentNullException("dictionary");

            if (type == typeof(Model))
            {
                Model result = new Model();
                foreach (var item in dictionary.Keys)
                {
                    if (dictionary[item] is string && item == "Values")
                        result.Values = new string[] { (string)dictionary[item] };
                    else if(item=="Values")
                        result.Values = (string[])((ArrayList)dictionary[item]).ToArray(typeof(string));

                }
                return result;
            }
            return null;
        }

        public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override IEnumerable<Type> SupportedTypes
        {
            get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(Model) })); }
        }
    }

您可以这样称呼它:

JavaScriptSerializer serializer = new JavaScriptSerializer();

ModelConverter sc = new ModelConverter();
serializer.RegisterConverters(new JavaScriptConverter[] { new ModelConverter() });


Model workingModel = serializer.Deserialize<Model>("{ Values : '2346' }");
Model workingModel1 = serializer.Deserialize<Model>("{ Values : ['2346'] }");
Model workingModel2 = serializer.Deserialize<Model>("{ Values : ['2346','3123'] }");

这是MSDN documentation for JavascriptConverter

答案 1 :(得分:0)

为什么不简单地使用

Model wontWorkModel = serializer.Deserialize<Model>("{ Values : ['test'] }");