So I'm using a WCF service to insert data in a DB, for this purpose I send my data in a POST to my WCF service and collect it using a DataContract as so :
JSON data sent by POST
{
"data":
{
"subsidiarySid":"0",
"storesid":"0",
"date":"2018-06-15",
"counters":
[
{
"nation":"France",
"count":"5"
},
{
"nation":"France",
"count":"5"
}
]
}
}
The DataContract
[DataContract(Name ="data")]
public class Count
{
[DataMember(Name ="subsidiarySid")]
public string subsidiarySid;
[DataMember(Name ="storeSid")]
public string storeSid;
[DataMember(Name = "date")]
public string date;
[DataMember(Name = "counters")]
public IEnumerable<Counter> counters;
}
[DataContract]
public class Counter
{
[DataMember(Name = "nationalitySid")]
public string nationalitySid;
[DataMember(Name = "count")]
public string count;
}
Method in Interface
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "count_customers")]
string PostCount(Count count);
Problem is when I try to access this object I get a null... Is my contract wrong or did I mess something elsewhere? Also can I get rid of the "data{}" at the start of the json (like havig directly my "subsidiarySid etc at the root of the json)?
Found my way after all, so I'm posting it as answer for future reference. What I did was to get the string attributes out of the DataContract (getting them by name in the OperationContract like this:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "count_customers")]
string PostCount(string subsidiarySid, string storeSid, string date, IEnumerable<Counter> counters);
And the DataContract
[DataContract(Name = "counter")]
public class Counter
{
[DataMember(Name = "nationalitySid")]
public string nationalitySid;
[DataMember(Name = "count")]
public string count;
}
Just removing the "Name" attribute in DataContract definition permitted me to ommit the unnecessary "data:{}" layer.