I have a JSON feed that looks like this (I removed some fields that aren't necessary for this example):
{
"total_count": 2,
"num_pages": 1,
"current_page": 1,
"balance": {
"amount": "0.00001199",
"currency": "BTC"
},
"transactions": [
{
"transaction": {
"id": "5018f833f8182b129c00002f",
"created_at": "2012-08-01T02:34:43-07:00",
"sender": {
"id": "5011f33df8182b142400000e",
"name": "User Two",
"email": "user2@example.com"
},
"recipient": {
"id": "5011f33df8182b142400000a",
"name": "User One",
"email": "user1@example.com"
}
}
},
{
"transaction": {
"id": "5018f833f8182b129c00002e",
"created_at": "2012-08-01T02:36:43-07:00",
"hsh": "9d6a7d1112c3db9de5315b421a5153d71413f5f752aff75bf504b77df4e646a3",
"sender": {
"id": "5011f33df8182b142400000e",
"name": "User Two",
"email": "user2@example.com"
},
"recipient_address": "37muSN5ZrukVTvyVh3mT5Zc5ew9L9CBare"
}
}
]
}
There are two types of transactions in this feed: internal transactions that have a recipient
, and external transactions that have a hsh
and recipient_address
.
I created the following classes to accomodate this structure:
So we have a base class for all paged results (PagedResult
) with a specific implementation for transactions (TransactionPagedResult
). This result has a collection containing 0..* transactions (abstract class Transaction
). They're not of the type Transaction
though, but of type InternalTransaction
or ExternalTransaction
which are implementations of Transaction
.
My question is how I can let JSON.NET handle this. I want JSON.NET to see whether the current transaction it's parsing is an InternalTransaction
or an ExternalTransaction
, and add the according type to the IEnumerable<Transaction>
collection in TransactionPagedResult
.
I created my own JsonConverter that I added as a property to the IEnumerable<Transaction>
with the [JsonConverter(typeof(TransactionCreationConverter))]
attribute, but this didn't work, I get the following error:
Additional information: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path 'transactions', line 1, position 218.
I understand this is because JSON.NET tries to deserialize the whole collection, but I want it to deserialize each object inside the collection one by one.
Anyone?