C#JsonConverter无法从JsonResult反序列化对象

时间:2018-01-09 19:16:11

标签: c# json

我有一个API方法,使用我的帮助方法将模型作为json返回

public static JsonResult ParseObjectToJsonResult<T>(T objectToParse) where T : class
{
    return new JsonResult(JsonConvert.SerializeObject(objectToParse));
}

然后在移动端,我试图将这个Json反序列化为相同的模型(简化):

return JsonConvert.DeserializeObject<T>([string with response]);

不幸的是我收到了错误,我不确定为什么......

  

Newtonsoft.Json.JsonSerializationException:转换值时出错   “{” 用户ID “:” 00f0299f-3210-45bb-ab6f-5995de30bf26" , “IsSuccess”:真, “消息”: “”}”   输入'Models.APIResponseModels.LoginResponseModel'。路径'',行   1,位置91。

我的模型看起来像:

JsonProperty(PropertyName = "UserId")]
        public string UserId { get; set; }

        [JsonProperty(PropertyName = "IsSuccess")]
        public bool IsSuccess { get; set; }

        [JsonProperty(PropertyName = "Message")]
        public string Message { get; set; }

有什么想法吗?

1 个答案:

答案 0 :(得分:8)

变化:

return new JsonResult(JsonConvert.SerializeObject(objectToParse));

return new JsonResult(objectToParse);

您需要对数据进行双重序列化。 JsonConvert将其序列化为字符串,然后JsonResult获取该字符串并将其再次序列化

(另外,将objectToParse重命名为其他内容。它没有被解析。解析是将字符串转换为某种数据结构的一组步骤。 #39;转向另一个方向 - 数据结构为字符串。)

相关问题