Home > Blockchain >  Correct way to adding to JSON in Foreach loop C#
Correct way to adding to JSON in Foreach loop C#

Time:03-21

I have code that give mi JSON file. But this JSON file have \ signs inside (string escape). How to change this code to remove \ signs?

public class Reservation
    {
        public string start { get; set; }
        public string end { get; set; }
    }

    [HttpGet]
    public IEnumerable<string> JSON()
    {
        var jsonString = "NO RESERVATIONS";

        var jsonList = new List<string>();

        foreach (var reservation in _context.ReservationModel)
        {
            var start = reservation.StartOfReservation.ToString("yyyy.MM.dd");
            var end = reservation.EndOfReservation.ToString("yyyy.MM.dd");


            var res = new Reservation
            {
                start = start,
                end = end,
            };

            jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(res);
            jsonList.Add(jsonString);

        }
        return jsonList;
    }

JSON:

["{\"start\":\"2022.03.22\",\"end\":\"2022.03.25\"}","{\"start\":\"2022.04.22\",\"end\":\"2022.04.25\"}"]

CodePudding user response:

your json file is invalid

[HttpGet]
public  string GetJsonString()
{
    ....

       var resList = new List<res>();

        foreach (var reservation in _context.ReservationModel)
        {
            var start = reservation.StartOfReservation.ToString("yyyy.MM.dd");
            var end = reservation.EndOfReservation.ToString("yyyy.MM.dd");


            var res = new Reservation
            {
                start = start,
                end = end,
            };

            resList.Add(res);

        }
        var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(resList);
        return jsonString;
}

but I higly recommed you to use this syntax, it will be automatically serialized to Json.

[HttpGet]
public List<Reservation>  GetJson()
{
    ....

       var resList = new List<res>();

        foreach (var reservation in _context.ReservationModel)
        {
          .....
        }
       
        return resList;
}

  • Related