2015-08-23 2 views
0

По какой-то причине объект HttpCookie не выполняет десериализацию от JSON. Я получаю эту ошибку -Deserialize HttpCookie объект от JSON

Невозможно заполнить тип списка System.Web.HttpValueCollection. Путь «ценности», линия .., положение ..

мне удалось десериализации JSON в пользовательский класс (HttpCookieModel), которые не имеют Values свойство, а затем перестроить HttpCookie из данных. Но нет ли более простого способа?

using Newtonsoft.Json; // v7.0.1 

public JsonResult GetCookie() { 
    return Json(new { Success = true, Username = model.UserName, Cookie = FormsAuthentication.GetAuthCookie(model.UserName, true) }); 
} 

private static void DoSomeTests() 
{ 
     // HttpWebRequest request.... 
     // Call GetCookie() 
     // ... 
     var httpResponse = (HttpWebResponse)request.GetResponse(); 
     using (var streamReader = new StreamReader(httpResponse.GetResponseStream(), true)) 
     { 
      res = streamReader.ReadToEnd(); 
     } 
     // Deserialize 
     try 
     { 
      MyResponse mr = JsonConvert.DeserializeObject<MyResponse>(res); 
     } 
     catch (Exception ex) 
     { 
      string message = ex.Message; // message: Cannot populate list type System.Web.HttpValueCollection. Path 'Values'.... 
     } 


    public class MyResponse 
    { 
     public bool Success { get; set; } 
     public string Username { get; set; } 
     // public HttpCookie Cookie { get; set; } // Problems deserializing Values collection. 
     public HttpCookieModel Cookie { get; set; } 
    } 

    // This model works - but is there a simpler way? 
    public class HttpCookieModel 
    { 
     public string Domain { get; set; } 
     public DateTime Expires { get; set; } 
     public bool HasKeys { get; set; } 
     public bool HttpOnly { get; set; } 
     public string Name { get; set; } 
     public string Path { get; set; } 
     public bool Secure { get; set; } 
     public bool Shareable { get; set; } 
     public string Value { get; set; } 

     public HttpCookie ConvertToHttpCookie() 
     { 
      HttpCookie result   = new HttpCookie(this.Name); 
      result.Domain    = this.Domain; 
      result.Expires    = this.Expires; 
      result.HttpOnly    = this.HttpOnly; 
      result.Path     = this.Path; 
      result.Secure    = this.Secure; 
      result.Shareable   = this.Shareable; 
      result.Value    = this.Value; 
      return result; 
     } 
    } 
} 

ответ

0

Возьмите ответ JSon и импортировать его здесь http://json2csharp.com/ это создаст необходимые классы, необходимые для правильного десериализация, то просто deserialise к классу RootObject (RootObject это имя по умолчанию, что json2csharp дает, изменить его на то, что соответствует вашим потребности

+0

Я уже создал этот класс - но это решение, которое я не хочу использовать. HttpCookie - это класс C#, а не пользовательский класс, но DeserializeObject не может десериализовать это, и я не знаю почему. – TamarG

0

MissingMemberHandling.Ignore Попробуйте:

Пример использования:

var jsonSerializerSettings = new JsonSerializerSettings(); 
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore; 

JsonConvert.DeserializeObject<YourClass>(jsonResponse, jsonSerializerSettings); 

С у наш код:

public class MyResponse 
    { 
     public bool Success { get; set; } 
     public string Username { get; set; } 
     public HttpCookie Cookie { get; set; } //use HttpCookie as normal 
    } 

Применить MissingMemberHandling.Ignore:

var jsonSerializerSettings = new JsonSerializerSettings(); 
jsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Ignore; 
MyResponse mr = JsonConvert.DeserializeObject<MyResponse>(res, jsonSerializerSettings); 
Смежные вопросы