ZeroByter
ZeroByter

Reputation: 374

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[]'

I know '[]' isnt ArrayList but I have no idea what else to say. Thanks

Upvotes: 0

Views: 3210

Answers (2)

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You can not assign ArrayList to the String[] array. 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.

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.

you you can use GenericCollections (typesafe) here to avoid the runtime exceptions. you can import the Generic Collections using following Namespace

using System.Collections.Generic;

then you can use List<T> instead of ArrayList.

Note: you need to mention the type upfront before using the List<T>.so it is typesafe and avoid the runtime exceptions.

you can use List asbelow:

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

Upvotes: 0

tobypls
tobypls

Reputation: 849

As you can read in the error, you have to convert your ArrayList to an array like this:

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

Upvotes: 1

Related Questions