PostAsJson没有正确序列化?

时间:2015-07-20 16:19:13

标签: c# json serialization

我正在尝试使用PostAsJsonAsync调用将模型POST到RESTful API并将返回序列化为对象。这似乎是微不足道的,因为我之前已经做了很多次,但我无法弄清楚为什么这不能正确序列化。下面我已经包含了C#模型,JSON响应以及它被序列化的内容。我还包括了我的代码。任何帮助将不胜感激。我应该指出,主要的不一致是错误字段。

C#型号:

public class AccountModel
{
    public int UniqueId { get; set; }
    public string Email { get; set; }
    public string UserId { get; set; }
    public string SingleSignOnId { get; set; }
    public string Password { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public int CompanyId { get; set; }
    public string EmployeeId { get; set; }
    public string Miscellaneous { get; set; }
    public bool Disabled { get; set; }
    public int UserTypeId { get; set; }
    public Dictionary<string, List<string>> Errors { get; set; }
}

JSON响应:

{  
   "Errors":{  
      "Password":[  
         "Password must meet 3 category requirements"
      ],
      "Account":[  
         "There was an error while creating a user."
      ]
   },
   "UniqueId":0,
   "Email":"email@email.com",
   "Password":"",
   "UserId":null,
   "SingleSignOnId":null,
   "FirstName":"First",
   "LastName":"Last",
   "Phone":null,
   "CompanyId":8888,
   "UserTypeId":4455668,
   "EmployeeId":null,
   "Disabled":false,
   "Miscellaneous":null,
}

模型序列化:

failure

代码:

public AccountModel Create(string sessionKey, AccountModel accountModel)
        {
            //Send Payload
            var req = new HttpClient();
            req.BaseAddress = new Uri(endpoint + "/Create");
            req.DefaultRequestHeaders.Accept.Clear();
            req.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            req.DefaultRequestHeaders.Add(Headers.SessionKey, sessionKey);
            var request = req.PostAsJsonAsync(endpoint + "/Create", accountModel);
            if (request.Result.IsSuccessStatusCode)
            {
                var data = request.Result.Content.ReadAsStringAsync().Result;
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AccountModel));
                return (AccountModel)serializer.ReadObject(request.Result.Content.ReadAsStreamAsync().Result);
            }
            else
            {
                throw new Exception(request.Result.Content.ReadAsStringAsync().Result);
            }
        }

1 个答案:

答案 0 :(得分:2)

这可能是DataContractJsonSerializer的一个问题。我能够使用Json.net库中的JsonSerializer来正确地反序列化字符串。

编辑: 如果您使用的是DataContractJsonSerializer,则需要提供自定义设置来反序列化字典

 DataContractJsonSerializerSettings settings = 
        new DataContractJsonSerializerSettings();
 settings.UseSimpleDictionaryFormat = true;
 DataContractJsonSerializer serializer = new   DataContractJsonSerializer(typeof(AccountModel), settings);

此解决方案仅适用于使用.Net 4.5+的情况。您始终可以尝试使用NewtonSoft.Json