locked
Why my JSON can not be deserialized by JsonSerializer.Deserialize? RRS feed

  • Question

  • User1052024640 posted

    Here is my code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net.Http;
    using System.Text.Json;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using WebApplication1.Models;
    
    // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
    
    namespace WebApplication1.Controllers
    {
        [Route("api/")]
        public class TestController : Controller
        {
            private readonly IHttpClientFactory _clientFactory;
            public TestController(IHttpClientFactory clientFactory)
            {
                _clientFactory = clientFactory;
            }        
            [HttpGet]
            [Route("Get")]
            public async Task<JsonResult> Get()
            {
                TestModel TestModel = new TestModel() {   Success = "123213",   SuccessRemark="555" };                        
                return Json(TestModel);
            }       
    
            [HttpGet]
            [Route("TestGet")]
            public async Task TestGet()
            {
                var request = new HttpRequestMessage(HttpMethod.Get,
                    string.Format("https://localhost:44345/api/Get"));
    
                var client = _clientFactory.CreateClient();
                client.Timeout = TimeSpan.FromSeconds(5);
                var response = await client.SendAsync(request);
                string Content = "";
                if (response.IsSuccessStatusCode)
                {
                    Content = await response.Content.ReadAsStringAsync();
                    var a = JsonSerializer.Deserialize(Content, typeof(TestModel));
                }
            }
            public class TestModel
            {
                public string Success { get; set; }
                public string SuccessRemark { get; set; }
            }
        }
    }
    

    While I access the URL 'https://localhost:44345/api/TestGet' try to deserialize the JSON to model. After deserialized, all the properties in variable 'a' are still null.

    Why it turns out to be this?

    Thursday, February 6, 2020 8:43 AM

Answers

  • User753101303 posted

    And how do you inspect "a"? What if you try :

    var a = JsonSerializer.Deserialize(Content, typeof(TestModel)) as TestModel; and then inspect a ?

    If the code looks correct I prefer to see in the code how the value is found to be wrong possibly using https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.assert?view=netframework-4.8#System_Diagnostics_Debug_Assert_System_Boolean_

    Sometimes it happens that the code is correct but the check is not (not looking at the correct db, I saw once someone telling its INSERT didn't work and all checks were fine, hje finally found that later in the code he left some code that deleted those rows etc...)


    If still not that the next thing I see would be a case sensitivity issue ?

    Edit: as you see I'm not really even trying to read the code that looks good. I'm trying to look at what happens for the serialized json string, how the value is found to be wrong etc... to close doors one after the other and hopefully narrow down in few steps what really happens. This is the kind of steps you could take even before asking for help if the problem still resists.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 6, 2020 9:31 AM

All replies

  • User753101303 posted

    Hi,

    My first move would be to look the value of the Content string rather than trying to guess by reading the code.

    Thursday, February 6, 2020 9:02 AM
  • User1052024640 posted

    The value of the content is

    "{\"success\":\"123213\",\"successRemark\":\"555\"}"

    It seems not any problem.

    Thursday, February 6, 2020 9:15 AM
  • User1052024640 posted

    I am not sure whether the problem is the code that produces the JSON or the code that deserializes JSON, so I post both in the question.

    Thursday, February 6, 2020 9:27 AM
  • User753101303 posted

    And how do you inspect "a"? What if you try :

    var a = JsonSerializer.Deserialize(Content, typeof(TestModel)) as TestModel; and then inspect a ?

    If the code looks correct I prefer to see in the code how the value is found to be wrong possibly using https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.assert?view=netframework-4.8#System_Diagnostics_Debug_Assert_System_Boolean_

    Sometimes it happens that the code is correct but the check is not (not looking at the correct db, I saw once someone telling its INSERT didn't work and all checks were fine, hje finally found that later in the code he left some code that deleted those rows etc...)


    If still not that the next thing I see would be a case sensitivity issue ?

    Edit: as you see I'm not really even trying to read the code that looks good. I'm trying to look at what happens for the serialized json string, how the value is found to be wrong etc... to close doors one after the other and hopefully narrow down in few steps what really happens. This is the kind of steps you could take even before asking for help if the problem still resists.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, February 6, 2020 9:31 AM
  • User1052024640 posted

    Thanks for reminding me of the case-sensitivity issue. It seems  .net core will automatically convert the first letter to low-case so that the JsonSerializer can not deserialize it while it is upper-case in the model.

    After I modified the first letter of the variable from upper-case to lower-case, all is ok!

    Thursday, February 6, 2020 9:42 AM
  • User753101303 posted

    Looks weird. Could it be that your app is configured to use a given serializer but that you are using another one which its own setting for your deserialization code ?

    As ASP.NET have support for doing that for you, my personal preference is just to avoid any explicit serialization/deserialization code and just let ASP.NET do this job. I'll have to give this a try. I assume this is ASP.NET Core 3.1 ?

    Thursday, February 6, 2020 10:27 AM
  • User1052024640 posted

    Yes, I am using the ASP.NET CORE 3.1

    Thursday, February 6, 2020 10:29 AM