2

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\"}"]
1

1 Answer 1

2

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;
}

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Serge. This is what I'm looking for!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.