【问题标题】:How to serialize ArrayList json如何序列化 ArrayList json
【发布时间】:2014-04-12 04:01:58
【问题描述】:

这是我的对象类:

public class personSerialize
{
    public string[] name { get; set; }
    public int number { get; set; }
};

而对象创建代码为:

personSerialize personObject = new personSerialize()
{
    name = people, //'people' is an ArrayList BTW
    number = peopleNum
};

它返回一个错误:

无法将类型“System.Collections.ArrayList”隐式转换为“string[]”

我知道 '[]' 不是 ArrayList,但我不知道还能说什么。谢谢

【问题讨论】:

  • 试试 -> name = (string[]) people.ToArray()

标签: c# json arraylist


【解决方案1】:

正如您在错误中看到的,您必须将您的 ArrayList 转换为这样的数组:

name = (string[]) people.ToArray( typeof(string) );

【讨论】:

    【解决方案2】:

    您不能将ArrayList 分配给String[] 数组。 您需要先将ArrayList 转换为Array,然后将结果转换为string[] 数组,因为ArrayList 包含objects 的集合而不是字符串。

    试试这个:

    name = (string[]) people.ToArray()
    

    建议:我们以前使用ArrayList,现在不是type safe,因为它的内容只有在运行时才能知道。

    您可以在此处使用 GenericCollections (typesafe) 来避免运行时异常。 您可以使用以下命名空间导入通用集合

    using System.Collections.Generic;

    那么您可以使用List<T> 而不是ArrayList

    注意:您需要在使用List<T>之前提前提及类型。因此它是类型安全的并避免运行时异常。

    您可以使用以下列表:

    List<string> list=new List<string>();
    list.Add("mystring1");
    list.Add("mystring2");
    list.Add("mystring3");
    

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 1970-01-01
      • 2013-12-14
      • 2017-10-06
      • 2015-06-28
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      相关资源
      最近更新 更多