Search code examples
c#asp.netjsonjson.netjson-deserialization

ASP.NET - Reading JSON file


I have a JSON file, please tell me how can I read that file. I have created a class file, and want to save JSON data in those class properties.

{
  "header": {
    "hid": "95845-5bhj-j908-o987-hhg5665",
    "datestamp": "2024-01-21"
  },
  "body": [
    {
      "hotelbooking": [
        {
          "Customer": {
            "Bookings": {
              "Profile": {
                "name": "Test",
                "dob": "1989-01-01",
                "mobile": "+919999999999",
                "address": "C-366,Saket,Delhi,INDIA,110044",
                "email": "[email protected]",
                "id": "GH2673677"
              },
              "roomtype": "DELUXE POOL VIEW"
            }
          },
          "BookingStatus": {
            "Confirm": {
              "amount": 4800
            },
            "Pax": "4",
            "currency": "THB",
            "bookDateTime": "2024-01-21T21:10:54Z",
            "address": "PATONG",
              "days": "4",
            "paymentstatus": "CONFIRM"
          },
          "RoomDetails": {
            "Rooms": [
              {
                "roomtype": "DELUXE GARDEN VIEW",
                "pricepernight": 1000,
                "currency": "THB",
                "refid": "0032514569"
              },
              {
                "roomtype": "DELUXE POOL VIEW",
                "pricepernight": 1200,
                "currency": "THB",
                "refid": "0069584214"
              },
              {
                "roomtype": "DELUXE SEA VIEW",
                "pricepernight": 1300,
                "currency": "THB",
                "refid": "0098541239"
              },
              
              {
                "roomtype": "SUITE POOL VIEW",
                "pricepernight": 2000,
                "currency": "THB",
                "refid": "0036521456"
              },
              {
                "roomtype": "SUITE POOL ACCESS",
                "pricepernight": 3000,
                "currency": "THB",
                "refid": "002651425"
              },
              {
                "roomtype": "PRESEDENTIAL SUITE INFINITY POOL",
                "pricepernight": 6000,
                "currency": "THB",
                "refid": "006985321"
              }
             ],
            "bookstartDate": "2024-04-09",
            "bookendDate": "2024-04-13"
          },
          "paymentmode": "cc",
          "creditcardNumber": "XXXXXXXXXXXX8976",
          "paymentRef": "bhgd73838-jdf73738"
        }
      ],
      "customerId": "yryu78876",
      "paymentbank": "DBS Bank",
      "secdeposit": "No",
      "OtherInfo": [
        {
          "ExtraBed": "No",
            "Breakfast": "Yes",
          "RefNo": "0069584214"
        }
      ]
    }
  ]
}

I am reading JSON with the following code, how can I read nodes of JSON?

I want to read all the nodes in the JSON file. I have created properties of all the nodes while saving the room type in the list.

This is the code in my class:

public class Body
{
    public List<Hotelbooking> hotelbooking { get; set; }
    public string customerId { get; set; }
    public string paymentbank { get; set; }
    public string secdeposit { get; set; }
    public List<OtherInfo> OtherInfo { get; set; }
}

public class Bookings
{
    public Profile Profile { get; set; }
    public string roomtype { get; set; }
}

public class BookingStatus
{
    public Confirm Confirm { get; set; }
    public string Pax { get; set; }
    public string currency { get; set; }
    public DateTime bookDateTime { get; set; }
    public string address { get; set; }
    public string days { get; set; }
    public string paymentstatus { get; set; }
}

public class Confirm
{
    public int amount { get; set; }
}

public class Customer
{
    public Bookings Bookings { get; set; }
}

public class Header
{
    public string hid { get; set; }
    public string datestamp { get; set; }
}

public class Hotelbooking
{
    public Customer Customer { get; set; }
    public BookingStatus BookingStatus { get; set; }
    public RoomDetails RoomDetails { get; set; }
    public string paymentmode { get; set; }
    public string creditcardNumber { get; set; }
    public string paymentRef { get; set; }
}

public class OtherInfo
{
    public string ExtraBed { get; set; }
    public string Breakfast { get; set; }
    public string RefNo { get; set; }
}

public class Profile
{
    public string name { get; set; }
    public string dob { get; set; }
    public string mobile { get; set; }
    public string address { get; set; }
    public string email { get; set; }
    public string id { get; set; }
}

public class Room
{
    public string roomtype { get; set; }
    public int pricepernight { get; set; }
    public string currency { get; set; }
    public string refid { get; set; }
}

public class RoomDetails
{
    public List<Room> Rooms { get; set; }
    public string bookstartDate { get; set; }
    public string bookendDate { get; set; }
}

This is my code to read the JSON file:

string jsonFile = @"E:\hotel.json";
var json = File.ReadAllText(jsonFile);

var jsonObject = JObject.Parse(json);
JArray hotelbodyArrary = (JArray)jsonObject["body"];

if (hotelbodyArrary != null)
{
    Body body = new Body();
    Hotelbooking ho = new Hotelbooking();
    foreach (var item in hotelbodyArrary)
    {
        
        ho.paymentmode = Convert.ToString(item["paymentmode"]);
        ho.creditcardNumber = Convert.ToString(item["creditcardNumber"]);
    }

}

I am not getting any value.


Solution

  • Your body array consists of multiple objects with the hotelbooking array. You need to iterate each object in the hotelbooking array to obtain the paymentmode and creditcardNumber values.

    Body body = new Body();
    body.hotelbooking = new List<Hotelbooking>();
    
    Hotelbooking ho = new Hotelbooking();
    foreach (var item in hotelbodyArrary)
    {
        JArray hotelBookingJArray = JArray.FromObject(item["hotelbooking"]);
        foreach (var hotelJObj in hotelBookingJArray)
        {
            ho.paymentmode = Convert.ToString(hotelJObj["paymentmode"]);
            ho.creditcardNumber = Convert.ToString(hotelJObj["creditcardNumber"]);
    
            body.hotelbooking.Add(ho);
        }
    }
    

    This will make it easier to deserialize it as classes and you are missing the Root class.

    Root root = JsonConvert.DeserializeObject<Root>(json);
    
    public class Root
    {
        [JsonProperty("header")]
        public Header Header { get; set; }
    
        [JsonProperty("body")]
        public List<Body> Body { get; set; }
    }