无法施放或转换System.String到类对象



我正在尝试从Web API

接收到的JSON字符串
try
{
    string r = await App.client.GetUser();
    App.Authentication = JsonConvert.DeserializeObject<ApiResult>(r);
    await DisplayAlert("TEST", App.Authentication.ToString(), "OK");
    Application.Current.MainPage = new Schedule();
}
catch (Exception p)
{
    await DisplayAlert("Getting Authentication failed", p.ToString(), "TEST");
}

但是它给出了错误:无法施放或转换system.string到app1.apiresult App.Authentication = JsonConvert.DeserializeObject<ApiResult>(r);

app.authentication:

public static ApiResult Authentication = new ApiResult();`

json字符串:

" " {\" status \":\" 0 \",\" message \":{\" id \":5,\ \" firstname \":\" john \",\" lastname \":\" doe \",\" email \":\" testemail@gmail.com \",\" password \ \":\" testpass \",\" CreationDate \":\" 2016-10-26T15:01:08 \",\" releid \":1,\ doorcode \'otor Code \\\\\\\\\\\\\\\\":9999}} "

apiresult类:

public class ApiResult
{
    public string status { get; set; }
    public Account message { get; set; }
}

帐户类:

public class Account
{
    public string status { get; set; }
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
    public DateTime CreationDate { get; set; }
    public int RoleID { get; set; }
    public int doorCode { get; set; }
}

完整错误消息:

{"错误转换值 " {"状态":" 0 "," messages ":{" ID ":5," firstName ":" john ",", " lastName ":":"doe "," email ":" testemail@gmail.com "," password ":" testpass "," creationdate ":" 2016-10-26T15:01:01:08 "," releid ":1,"门代码":9999}}} " 键入'app1.apiresult'。路径'',第1行,位置232。"}

看来,您收到的JSON已被序列化两次 - 首先是从ApiResultstring,然后再次到string

""{\"status\":\"0\",\"message\":...

您的调试器可能会添加第一个双引号,但是第二个引号(逃脱的" One)似乎确实是您正在处理的数据的一部分。错误消息也很有意义,它值得将string划分,然后尝试将其投射到ApiResult

尝试将数据当作字符串,然后然后将其结果列为ApiResult,以确保是这种情况 - 如果是这样,则需要更改服务器代码。

下面的代码沿着我的c.evenhuis答案为我工作,

   var content = response.Content;              
   var jsonResult = JsonConvert.DeserializeObject(content).ToString();
   var result= JsonConvert.DeserializeObject<Model>(jsonResult);

这里的内容类似于 - " " {\" id \":\" 92209 \",\" operatorId \":100000,\" status \":true,.....

尝试使用app.authentication = jobign.parse(request.content.content.readasstringasync()。结果);

最新更新