json - 在 WCF 中从 POST 检索数据时出现问题
问题描述
因此,我使用 WCF 服务在数据库中插入数据,为此我将 POST 中的数据发送到我的 WCF 服务并使用 DataContract 收集它,如下所示:
POST 发送的 JSON 数据
{
"data":
{
"subsidiarySid":"0",
"storesid":"0",
"date":"2018-06-15",
"counters":
[
{
"nation":"France",
"count":"5"
},
{
"nation":"France",
"count":"5"
}
]
}
}
数据合约
[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;
}
接口中的方法
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "count_customers")]
string PostCount(Count count);
问题是当我尝试访问这个对象时,我得到一个空值......我的合同是错误的还是我在其他地方搞砸了?我也可以摆脱 json 开头的“data{}”(比如直接在 json 的根目录下使用我的“subsidiarySid 等)吗?
解决方案
毕竟找到了自己的方式,所以我将其发布为将来参考的答案。我所做的是从 DataContract 中获取字符串属性(在 OperationContract 中按名称获取它们,如下所示:
[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);
和数据合同
[DataContract(Name = "counter")]
public class Counter
{
[DataMember(Name = "nationalitySid")]
public string nationalitySid;
[DataMember(Name = "count")]
public string count;
}
只需删除 DataContract 定义中的“名称”属性,我就可以省略不必要的“数据:{}”层。
推荐阅读
- javascript - 如何在一行中默认导出命名导入?
- javascript - 如何删除括号和括号内的内容?
- python - 如何以相反的顺序从生成器中获取元素?
- javascript - 是否可以在 Node.js 上使用 js 资源或 react Native?
- c - 如何使用scanf()和while循环将字符串从stdin读入c编程中的二维数组?
- regex - 如何匹配部分精确和部分可变的文本
- backup - 小团队如何对源代码进行安全备份?
- python - 如何更改 odoo 12 中的 many2one 值字段名称?
- r - r-markdown - 动态多行标题与第二行相同
- java - Jersey 休息请求通用类型