Home > Back-end >  Cannot correctly parse my object from Json returned from my C# Web API
Cannot correctly parse my object from Json returned from my C# Web API

Time:07-05

I have searched until my eyes are bleeding but alas no answers.

I have a class called Booking.

public class Booking
    {     

        [Key]
        public int Id { get; set; }

        [Required]
        public int RoomNumber { get; set; }

        [Required]
        public string? ClientName { get; set; }
    }

The API method is

[HttpGet]        
        public async Task<JsonResult> Get(int id)
        {
            Booking? booking = await _bookingRepository.FindByIdAsync(id);

            if (booking == null)
            {
                return new JsonResult(NotFound());
            }
            return new JsonResult(Ok(booking));
        }

The Client is

protected static async Task<Booking?> GetAsync<Booking>(HttpClient httpClient)
        {
            HttpResponseMessage response = await httpClient.GetAsync("https://localhost:7139/api/HotelBooking?id=5");
            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                string msg = await response.Content.ReadAsStringAsync();
                return default(Booking);
            }
            else if (response.IsSuccessStatusCode)
            {
                string msg = await response.Content.ReadAsStringAsync();
                Booking? booking = JsonConvert.DeserializeObject<Booking>(msg);
                //Booking? booking = await response.Content.ReadFromJsonAsync<Booking>();
                
                return booking;
            }           
            else
            {
                string msg = await response.Content.ReadAsStringAsync();
                Console.WriteLine(msg);
                throw new Exception(msg);
            }
        }

The value in msg is

{
  "Value": {
    "Id": 5,
    "RoomNumber": 100,
    "ClientName": "Nelms, Anthony"
  },
  "Formatters": [],
  "ContentTypes": [],
  "DeclaredType": null,
  "StatusCode": 200
}

The result: I have a Booking object that is instantiated by the JsonConvert.DeserializeObject line of code, but all three values are missing. The string is null and the two ints are zero.

I believe the problem is that the section "Value" is "hiding" my data. I am not sure how to read the data from response.Content.

This is my first attempt at Http. Any help would be appreciated.

CodePudding user response:

you have to add a root Message class to deserialize properly

    string msg = await response.Content.ReadAsStringAsync();

    var message = JsonConvert.DeserializeObject<Message>(msg);

    return message.Booking;

     public class  Message
    {
        [JsonProperty("Value")]
        public Booking Booking { get; set; }

       //optional properties, you can remove them if you don't need

        public List<object> Formatters { get; set; }
        public List<object> ContentTypes { get; set; }
        public object DeclaredType { get; set; }
        public int StatusCode { get; set; }
       
    }

    public class Booking
    {
        public int Id { get; set; }
        public int RoomNumber { get; set; }
        public string ClientName { get; set; }
    }

CodePudding user response:

Can you try replacing msg with msg.Result in below line?

JsonConvert.DeserializeObject<Booking>(msg.Result);
  • Related