Deserialize Two dimensional array

Apr 13, 2012 at 12:23 PM

I have a property of a results set that is a two dimensional array instead of an array of objects. I cannot automatically deserialize this property along with all the other properties in the set (which are arrays of objects i.e. with property names) as it is a two dimensional array

I want to deserialize this two dimensional array to a List<CustomType> as I know what the values in the array represent in advance but JSON.NET correctly throws an error as it cannot automatically convert an array of values into a custom type.

How can this be achieved?

____

snippet of feed:

  "results": [
    [
      111902,
      1,
      211,
      29,
      1,
      "2011-12-22T17:28:18Z",
      211
    ],
    [
      116764,
      1,
      11448,
      29,
      3,
      "2012-03-05T10:54:37Z",
      0
    ]
]

Apr 13, 2012 at 1:50 PM

I think the solution has something to do with a custom JsonConverter...trying to work it out

Apr 13, 2012 at 5:14 PM
Edited Apr 14, 2012 at 1:43 PM

Yes, custom JsonConvertor.

 

Used this to point me in the right direction:

http://stackoverflow.com/questions/9452901/cannot-deserialize-json-array-into-type-json-net

Came up with:

 

            public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
            {

                JArray j = new JArray();
// add each value into a JArray
                while (reader.Read())
                { 
// check if we are at the end of the single result array
                    if (reader.TokenType == JsonToken.EndArray)
                        break;
                    j.Add(reader.Value);
               
                }


// then put the values into your object   
                YourCustomObject order = new YourCustomObject ();


                order.orderId = int.Parse(j[0].ToString());
                order.orderTypeId = int.Parse(j[1].ToString());
                order.contactId = int.Parse(j[2].ToString());

//etc.


                return order;
            }