我正在使用Windows 10 Universal应用程序,在尝试从我的webAPI接收数据时,我的代码如下:
try
{
string _serviceUrl = Constants.BaseUrl + "api/RegisterBindingModels?email=" + Useremail;
HttpClient client = new HttpClient();
HttpResponseMessage responce = await client.GetAsync(new Uri(_serviceUrl));
if (responce.Content != null)
{
var obj = await responce.Content.ReadAsStringAsync();
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Ignore;
var rcvdData = JsonConvert.DeserializeObject<RegisterModel>(obj, settings);
}
}
catch (Exception)
{
throw;
}
当此代码运行时,Obj获得以下JSON,这是预期的:
{ "UserDetails":{ "UserId":1, "FullName":"sample string 2", "Username":"sample string 3", "ICEFullName":"sample string 4", "ICEMobileNumber":5, "DoctorFullName":"sample string 6", "DoctorMobileNumber":7 }, "UserId":1, "Email":"akshay@gmail.com", "Password":"addsFABBS!2", "ConfirmPassword":"addsFABBS!2" }
然而,var rcvdData具有所有空值:
RegisterModel如下:
namespace APIValueSetterTest.Model
{
using System.Runtime.Serialization;
[DataContract]
public class RegisterModel
{
public int UserId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public UserDetails UserDetails { get; set; }
}
}
和UserDetails模型如下:
namespace APIValueSetterTest.Model
{
using System.Runtime.Serialization;
[DataContract]
public class UserDetails
{
public int UserId { get; set; }
public string FullName { get; set; }
public string Username { get; set; }
public string ICEFullName { get; set; }
public int ICEMobileNumber { get; set; }
public string DoctorFullName { get; set; }
public int DoctorMobileNumber { get; set; }
}
}
我需要帮助,我哪里出错了?
答案 0 :(得分:1)
问题是您已使用[DataContract]
标记了类型,但未标记要使用[DataMember]
序列化的每个成员。明确的数据合同序列化是选择性的,如Using Data Contracts中所述:
您还可以使用DataContractAttribute和DataMemberAttribute属性明确创建数据合同。这通常通过将DataContractAttribute属性应用于该类型来完成。此属性可以应用于类,结构和枚举。 然后必须将DataMemberAttribute属性应用于数据协定类型的每个成员,以指示它是数据成员,即应该序列化。有关更多信息,请参阅Serializable Types。
由于json.net支持数据合同,如docs所述,您需要删除[DataContract]
,或将[DataMember]
添加到所有可序列化成员。