当前位置:  开发笔记 > 编程语言 > 正文

在创建JavascriptConverter时,如何返回数组?

如何解决《在创建JavascriptConverter时,如何返回数组?》经验,为你挑选了1个好方法。



1> bdukes..:

JavaScriptConverters只能创建JSON对象,而不能创建其他类型.如果只想返回一个数组,则需要将对象转换为.NET数组,然后将其发送给该Serialize方法.

例如,要返回Person对象数组,请执行以下操作:

IList people = ...;
var serializer = new JavaScriptSerializer();
serializer.Serialize(people.ToArray());

或者,如果您正在创建一个JSON对象并希望其中一个属性是一个数组,那么您应该使用自定义JavaScriptConverter,如下所示:

public class ExampleConverter : JavaScriptConverter
{
    /// 
    /// Gets a collection of the supported types
    /// 
    /// An object that implements  that represents the types supported by the converter. 
    public override IEnumerable SupportedTypes
    {
        get
        {
            return new ReadOnlyCollection(new Type[] { typeof(MyExampleType) });
        }
    }

    /// 
    /// Converts the provided dictionary into an object of the specified type. 
    /// 
    /// An  instance of property data stored as name/value pairs. 
    /// The type of the resulting object.
    /// The  instance. 
    /// The deserialized object. 
    /// We only serialize
    public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
    {
        throw new InvalidOperationException("We only serialize");
    }

    /// 
    /// Builds a dictionary of name/value pairs
    /// 
    /// The object to serialize. 
    /// The object that is responsible for the serialization. 
    /// An object that contains key/value pairs that represent the object’s data. 
    ///  must be of the  type
    public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
    {
        MyExampleType example = obj as MyExampleType;
        if (example == null)
        {
            throw new InvalidOperationException("object must be of the MyExampleType type");
        }

        IDictionary jsonExample = new Dictionary();
        jsonExample.Add("arrayMember", example.People.ToArray());
        jsonExample.Add("otherMember", example.Member);

        return jsonExample;
    }
}

这被称为这样:

JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] { new ExampleConverter() });
return serializer.Serialize(myExample);

推荐阅读
郑小蒜9299_941611_G
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有