public class SomeObject
{
public IList arrayList;
public SomeObject()
{
arrayList = new ArrayList();
arrayList.Add(0);
}
}
The only change I've made is replace the type of the public arrayList field with IList. When you will export an instance of SomeObject, the arrayList field will get written out as a JSON Array irrespective of the concrete type of the instance referred by the field. When you will import a SomeObject instance, however, Jayrock will instantiate the type JsonArray and store a reference to it in the arrayList field. If you code entirely against IList then this detail should not make any difference whatsoever because JsonArray, like ArrayList, implements IList.
In short, here's how you'd import a JSON Array as a read/write list:
IList list = (IList) JsonConvert.Import(typeof(IList), "[1,2,3]");
If you insist on working with ArrayList, you could write the code like this:
ArrayList list = new ArrayList((IList) JsonConvert.Import(typeof(IList), "[1,2,3]"));
Lastly, if the array elements are homogeneous, then you could just use a typed array like this:
int[] nums = (int[]) JsonConvert.Import(typeof(int[]), "[1,2,3]"));
Hope this helps.
- Atif
-----Original Message-----
From: jay...@googlegroups.com [mailto:jay...@googlegroups.com] On Behalf Of psy...@gmail.com
Sent: Thursday, March 01, 2007 9:06 PM
To: Jayrock
Subject: [Jayrock] What about Serializing/Deserializing ArrayLists?
I'm trying to parse the below simple class into a Json format:
public class SomeObject
{
public ArrayList arrayList;
public SomeObject()
{
arrayList = new ArrayList();
arrayList.Add(0);
}
}
In my main parse function I'm using the following code:
string jsonStr = JsonConvert.ExportToString(new SomeObject());
SomeObject someObjectInstance = JsonConvert.Import(typeof(SomeObject),
jsonStr) as SomeObject;
But the execution is halting at Import line and generating the
following error:
An unhandled exception of type 'Jayrock.Json.JsonException' occurred
in Jayrock.Json.dll
Additional information: Cannot import System.Collections.ArrayList
from a JSON Array value.
How I can parse an ArrayList correctly?
Thanks in advance,
Alex