[英]How to serialize ArrayList json
So this is my object class: 这是我的对象类:
public class personSerialize
{
public string[] name { get; set; }
public int number { get; set; }
};
And the object creation code is: 对象创建代码为:
personSerialize personObject = new personSerialize()
{
name = people, //'people' is an ArrayList BTW
number = peopleNum
};
And it returns one error: 它返回一个错误:
Cannot implicitly convert type 'System.Collections.ArrayList' to 'string[]' 无法将类型'System.Collections.ArrayList'隐式转换为'string []'
I know '[]' isnt ArrayList but I have no idea what else to say. 我知道'[]'不是ArrayList,但我不知道还有什么要说的。 Thanks
谢谢
如您所见,您必须将ArrayList
转换为这样的数组:
name = (string[]) people.ToArray( typeof(string) );
You can not assign ArrayList
to the String[]
array. 您不能将
ArrayList
分配给String[]
数组。 You need to fist convert your ArrayList
into the Array
and then cast the result into string[]
array as ArrayList
contains collection of objects
not strings. 您需要
ArrayList
转换为Array
,然后将结果转换为string[]
数组,因为ArrayList
包含objects
集合而不是字符串。
Try This: 尝试这个:
name = (string[]) people.ToArray()
Suggestion: we used to use ArrayList
in olden days and it is not type safe
as its content only be know at runtime. 建议:我们过去曾经使用
ArrayList
,它的type safe
因为它的内容只能在运行时知道。
you you can use GenericCollections (typesafe)
here to avoid the runtime exceptions. 您可以在此处使用GenericCollections
(typesafe)
以避免运行时异常。 you can import the Generic Collections using following Namespace 您可以使用以下命名空间导入通用集合
using System.Collections.Generic;
then you can use List<T>
instead of ArrayList
. 那么您可以使用
List<T>
而不是ArrayList
。
Note: you need to mention the type upfront before using the List<T>
.so it is typesafe and avoid the runtime exceptions. 注意:在使用
List<T>
之前,您需要提前提及类型,因此它是类型安全的,并且避免了运行时异常。
you can use List asbelow: 您可以如下使用列表:
List<string> list=new List<string>();
list.Add("mystring1");
list.Add("mystring2");
list.Add("mystring3");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.