C# Could not Cast or Convert System.String to Class object

前端 未结 4 1487
甜味超标
甜味超标 2021-01-01 09:47

I am trying to deserialize a JSON string received from a Web API

try
{
    string r = await App.client.GetUser();

    App.Authentication = JsonConvert.Deser         


        
相关标签:
4条回答
  • 2021-01-01 10:27

    Below code worked for me along the lines of to C.Evenhuis answer,

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

    Here Content is similar to - "\"{\\"Id\\":\\"92209\\",\\"operatorId\\":100000,\\"Status\\":true, .....

    0 讨论(0)
  • 2021-01-01 10:29

    Try using App.Authentication = JObject.Parse(request.Content.ReadAsStringAsync().Result);

    0 讨论(0)
  • 2021-01-01 10:30

    It appears that the json you receive has been serialized twice - first from ApiResult to string, then to string again:

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

    The first double-quote might be added by your debugger, but the second (the escaped \" one) really appears to be part of the data you're processing. The error message also makes sense this way, it deserializes a string and then attempts to cast it to an ApiResult.

    Try deserializing the data as a string and then deserializing its result to an ApiResult, to be sure this is the case - and if so, the server code will need to be changed.

    0 讨论(0)
  • 2021-01-01 10:37

    your data model,

       var r = new ApiResult
                {
                    status = "0",
                    message = new Account()
                    {
                        status = "0",
                        CreationDate = DateTime.Now,
                        Email = "foo@foo.com",
                        FirstName = "Trump",
                        ID = 1,
                        LastName = "Fck",
                        Password = "111",
                        RoleID = 1,
                        doorCode = 222
                    }
                };
    
    
    var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(r);
    
    var apiObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult>(jsonResult);
    

    jsonResult:

    to problem look here App.client.GetUser();

    0 讨论(0)
提交回复
热议问题