I can easily handle standard JSON responses using DataContractJsonSerializer
and it works just fine. Now I have to deal with an REST API that returns some properties either as object or as an array.
Example "As Object":
{
"collection": {
"type3": {
"param5": "foo",
"param6": "bar"
}
}
}
Example "As Array":
{
"collection": [
"type1": {
"param1": "lorem",
"param2": "ipsum"
},
"type2": {
"param3": "hello",
"param4": "world"
}
]
}
As you can see, the property collection
behaves a little bit strange. If only one "Type" is available, the API returns an object. If more types are available, the API returns an array of objects. Additionaly each type of object is defined by its key type1
, type2
or type3
.
I am pretty stuck at the point of organizing DataContract
and DataMember
. I do not know how to define the collection
property correctly.
I am stuck here:
using System.Runtime.Serialization;
namespace Demo
{
[DataContract]
public class Response
{
// [DataMember(Name = "collection")]
// public Type1[] collection { get; set; }
// public Type2[] collection { get; set; }
// public Type3[] collection { get; set; }
// [DataMember(Name = "collection")]
// public Collection collection { get; set; }
// ???
}
[DataContract]
public class Collection
{
[DataMember(Name = "type1")]
public Type1 type1 { get; set; }
[DataMember(Name = "type2")]
public Type2 type2 { get; set; }
[DataMember(Name = "type3")]
public Type3 type3 { get; set; }
}
[DataContract]
public class Type1
{
[DataMember(Name = "param1")]
public string param1 { get; set; }
[DataMember(Name = "param2")]
public string param2 { get; set; }
}
[DataContract]
public class Type2
{
[DataMember(Name = "param3")]
public string param3 { get; set; }
[DataMember(Name = "param4")]
public string param4 { get; set; }
}
[DataContract]
public class Type3
{
[DataMember(Name = "param5")]
public string param5 { get; set; }
[DataMember(Name = "param6")]
public string param6 { get; set; }
}
}
Can anyone tell how to handle this situation correctly? Thanks in advance!