This project has moved. For the latest updates, please go here.

Create an array from a single instance

May 30, 2011 at 6:25 PM

I'm calling an API that incorrectly returns arrays with a single instance as an object. I don't have any control over this API, otherwise I would fix it. I can't tell ahead of time whether the property value will be a List<Child> or a Child.

To make the deserializer more tolerant, I added the following code to JsonSerializerInternalReader.CreateObject().

JsonArrayContract arrayContract = contract as JsonArrayContract;
if (arrayContract != null)
    JsonObjectContract instanceContract = Serializer.ContractResolver.ResolveContract(arrayContract.CollectionItemType) as JsonObjectContract;
    object instance;
    if (existingValue == null)
        instance = CreateAndPopulateObject(reader, instanceContract, id);
        instance = PopulateObject(existingValue, reader, instanceContract, id);
    IList array = arrayContract.DefaultCreator() as IList;
    return array;

Hope this helps somebody.

Mar 6, 2012 at 11:25 PM

I have the same issue, my class property is List<string>, but the incoming Json for this property could be either string or List<string> depending on clients selection from checkboxes.

Do you have an example code of the above working?