Kyle
Kyle

Reputation: 2379

PostAsJson not serializing correctly?

I am attempting to use a PostAsJsonAsync call to POST a model to a RESTful API and serialize the return into an object. This seems trivial as I've done this plenty times before, but I can not figure out why this is not serializing correctly. Below I have included the C# Model, JSON Response and what it is serialized into it. I've also included my code. Any help would be greatly appreciated. I should point out that the main inconsistency is with the Errors field.

C# Model:

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 Response:

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

Model serialized:

failure

Code:

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);
            }
        }

Upvotes: 0

Views: 944

Answers (1)

KnightFox
KnightFox

Reputation: 3252

This might be an issue with DataContractJsonSerializer. I was able to use JsonSerializer from Json.net library to deserialize the string correctly.

EDIT: If you are using DataContractJsonSerializer, you need to provide custom settings to deserialize dictionary

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

This solution is only applicable if you are using .Net 4.5+. You can always try using NewtonSoft.Json

Upvotes: 2

Related Questions