【问题标题】:deserialize custom object returned from web api反序列化从 web api 返回的自定义对象
【发布时间】:2016-07-26 01:36:18
【问题描述】:

客户端向 web api 方法发出获取请求并获取一个对象作为响应,问题是我无法反序列化这个对象..

客户端方法,向web api发出get请求

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

【问题讨论】:

    标签: asp.net-mvc asp.net-web-api


    【解决方案1】:

    您没有告诉反序列化器要反序列化到什么。这个

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

    反序列化为一个对象,然后尝试将该对象转换为User,这将失败。你需要使用泛型方法:

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

    如果 JSON 名称和类名/结构不同 Changing property names for serializing,您完全有可能需要做更多的工作。

    【讨论】:

    • 是的,但这次我面对的是这个编辑过的帖子。有什么建议吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2021-06-24
    相关资源
    最近更新 更多