反序列化自定义对象从网页API返回

问题描述:

客户做出get请求的Web API方法,并得到一个对象作为响应的问题是我不能desirialize这个对象..反序列化自定义对象从网页API返回

客户端方法,使GET请求的Web API

HttpClient client = new HttpClient(); 
       client.BaseAddress = new Uri("http://localhost:57752"); 
       HttpResponseMessage response = client.GetAsync("api/Auth/Login/" + user.Username + "/" + user.Password).Result; 
       JsonResult result = null; 
       if (response.IsSuccessStatusCode) 
       { 
        result = response.Content.ReadAsAsync<JsonResult>().Result; 
        JavaScriptSerializer json_serializer = new JavaScriptSerializer(); 
        User validUser = json_serializer.Deserialize<User>(result.Data.ToString());//Throws Exp. 
       } 

我想干脆把从API到VALIDUSER返回此对象实例..

错误消息:

无法将类型“System.String”的对象键入 “MongoDB.Bson.ObjectId”

这里有型号:

public abstract class EntityBase 
{ 
    [BsonId] 
    public ObjectId Id { get; set; } 
} 

public class User : EntityBase 
    { 
     //public string _id { get; set; } 
     [Required] 
     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 5)] 
     [DataType(DataType.Text)] 
     [Display(Name = "Username")] 
     public string Username { get; set; } 

     [Required] 
     [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
     [DataType(DataType.Password)] 
     [Display(Name = "Password")] 
     public string Password { get; set; } 

     public void EncryptPassword() 
     { 
      Password = Encrypter.Encode(this.Password); 
     } 

     [DataType(DataType.Password)] 
     [Display(Name = "Confirm password")] 
     [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
     public string ConfirmPassword { get; set; } 
    } 

你不告诉解串器如何反序列化。此

User validUser = (User)json_serializer.DeserializeObject(result.Data.ToString()); 

反序列化到一个对象,然后尝试施放该对象作为User,这是会失败。您需要使用泛型方法:

User validUser = json_serializer.Deserialize<User>(result.Data.ToString()); 

这是完全有可能的,你需要做更多的工作,如果JSON的名称和类名/ struictures不同Changing property names for serializing

+0

是的,但这一次,我面对这个编辑后。有什么建议? – TyForHelpDude