Reputation: 5002
Client make get request to web api method and get an object as response the problem is I cant desirialize this object..
client method, making get request to 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.
}
I want to simply put this object instance returned from api to validUser..
error message:
Cannot convert object of type 'System.String' to type 'MongoDB.Bson.ObjectId'
here are models:
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; }
}
Upvotes: 0
Views: 287
Reputation: 7211
You're not telling the deserializer what to deserialize to. This
User validUser = (User)json_serializer.DeserializeObject(result.Data.ToString());
deserializes into an object and then attempts to cast that object as a User
, which is going to fail. You need to use the generic method:
User validUser = json_serializer.Deserialize<User>(result.Data.ToString());
It's entirely possible you will need to do more work if the JSON names and the class names/struictures are different Changing property names for serializing.
Upvotes: 2