【发布时间】:2020-11-20 07:58:21
【问题描述】:
我有一个网络服务,我想发布 JSON 数据。 我想把提交的数据序列化成一个类,有些序列化的数据总是返回null。
这是 json 有问题的部分:
"contacts": {
..."1": {
"name": "tesz1",
"phone": "3600000000",
"email": null,
"title": null,
"try_before_reach" : 0
},
"2": {
"name": "tesz1",
"phone": "3600000000",
"email": null,
"title": null,
"try_before_reach" : 0
}
}...
这是课程:
....
[DataMember(Name = "contacts")]
public Dictionary<string, Contact> contacts { get; set; }
}
[DataContract]
public class Contact
{
[DataMember(Name = "name")]
public string name { get; set; }
[DataMember(Name = "phone")]
public string phone { get; set; }
[DataMember(Name = "email")]
public string email { get; set; }
[DataMember(Name = "title")]
public string title { get; set; }
[DataMember(Name = "try_before_reach")]
public int try_before_reach { get; set; }
}
网络服务:
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/VCC/", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
Task<WebhookResponse> ResponseAsync(VCCModel request);
}
并且 request.Contact 每次都返回 null。
有人知道问题可能是什么吗?
非常感谢。
【问题讨论】:
-
“webservice”是指wcf web 服务?或者是其他东西?请指定您使用的确切框架和版本,因为不同的版本使用不同的 JSON 序列化程序。
-
你的班级结构看起来不错。这应该被反序列化。如何调用服务和代码进行序列化和反序列化。请分享。
-
因为如果你真的在使用wcf,那么请注意wcf 使用的
DataContractJsonSerializer将字典序列化为键/值数组而不是对象,请参阅Collections, Dictionaries and Arrays。虽然可以为独立序列化修改此行为,但无法将必要的设置传递到 WCF。 -
是的,我正在使用 wcf。您能否建议我一个解决方案,如何使用 DataContractJsonSerializer 对其进行序列化,或者是否可以以某种方式替换序列化程序?
-
你能改成 JSON 格式吗?按照
DataContractJsonSerializer的要求格式化您的 JSON 要容易得多。
标签: c# json wcf json-deserialization datacontractjsonserializer