I have a Json object as follows:
{
"response" : {
"method" : "switchvox.currentCalls.getList",
"result" : {
"current_calls" : {
"current_call" : **[**
{
"provider" : "ThinkTel",
"start_time" : "2014-11-30 02:24:52",
"duration" : "5",
"to_caller_id_number" : "800",
"state" : "ivr",
"from_caller_id_name" : "<unknown>",
"to_caller_id_name" : "Main Answer Queue",
"format" : "ulaw",
"from_caller_id_number" : "9999999999",
"id" : "SIP/1234567890-08682a00"
},
{
"provider" : "ThinkTel",
"start_time" : "2014-11-30 02:24:50",
"duration" : "7",
"to_caller_id_number" : "800",
"state" : "ivr",
"from_caller_id_name" : "<unknown>",
"to_caller_id_name" : "Main Answer Queue",
"format" : "ulaw",
"from_caller_id_number" : "1111111111",
"id" : "SIP/9876543210-08681350"
}
**]**,
"total_items" : "2"
}
}
}
}
My classes were built using http://json2csharp.com
Everything is good until my
New Data allCalls = JsonConvert.DeserializeObject<Data>(json);
gets only 1 or 0 call in the array (if there is more than 1, all works). The [] in Json objects are removed when there is only 1 call and 0 calls, the whole current_call block is not there.
Here is how it looks without calls:
{
"response" : {
"method" : "switchvox.currentCalls.getList",
"result" : {
"current_calls" : {
"total_items" : "0"
}
}
}
}
And here how it looks with only 1 call:
{
"response" : {
"method" : "switchvox.currentCalls.getList",
"result" : {
"current_calls" : {
"current_call" : {
"provider" : "Internal",
"start_time" : "2014-11-30 19:15:44",
"duration" : "250",
"to_caller_id_number" : "777",
"state" : "talking",
"from_caller_id_name" : "<unknown>",
"to_caller_id_name" : "<unknown>",
"format" : "ulaw->ulaw",
"from_caller_id_number" : "231",
"id" : "SIP/231-b4066e90"
},
"total_items" : "1"
}
}
}
}
I get the following error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'WindowsService1.Service1+CurrentCall[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error I either need to change the JSON to a JSON array (e.g. [1,2,3]) or deserialized type to become normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
I understand what the error means but I don't now how to approach it in my situation.
current_call
is sometimes an object and sometimes an array, you will need to use aJsonConverter
to handle this. See How to handle both a single item and an array for the same property using JSON.net The accepted answer has aSingleOrArrayConverter<T>
class that you should be able to use here. – Brian Rogerscurrent_call
is not null, like you said. That, along with the converter, should do the trick. – Brian Rogers