JavaScriptConverters只能创建JSON对象,而不能创建其他类型.如果只想返回一个数组,则需要将对象转换为.NET数组,然后将其发送给该Serialize
方法.
例如,要返回Person对象数组,请执行以下操作:
IListpeople = ...; 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 public override IEnumerablethat represents the types supported by the converter. SupportedTypes { get { return new ReadOnlyCollection (new Type[] { typeof(MyExampleType) }); } } /// /// Converts the provided dictionary into an object of the specified type. /// /// Aninstance 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(IDictionarydictionary, 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. ///public override IDictionary must be of the type 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);