Search code examples
c#jsonio

c# .net 6 JSON saves with escapes and qouble quote start and end


For the life of me I cannot figure out why a serialized string of correct json is saving with qouble quotes and escapes.

Example data: string variable sent to serializer:

{"cidrs":[{"cidr":null,"failed":1,"firstSeen":null,"lastSeen":null}]}

Saved from string variable:

"{\"cidrs\":[{\"cidr\":null,\"failed\":1,\"firstSeen\":null,\"lastSeen\":null}]}"

Example method writing to file:

using (StreamWriter sw = File.AppendText(CIDRTrackingLocation))
 {
     sw.WriteLine(JsonConvert.SerializeObject(serialized));
 }

that's it, super basic but some reason ruining the saved JSON string.

tried loading string into a new string variable then writing that new string. Sent dummy data directly to method within double quotes, shows the same as mentioned but writes with double quotes and escapes.


Solution

  • You have to serialize object instead of string. There is no sense in serializing of JSON string. You can output it to stream as is. Example of object serialization:

    using System;
    using Newtonsoft.Json;
    
    public class CidrData
    {
        public string cidr { get; set; }
        public int failed { get; set; }
        public DateTime? firstSeen { get; set; }
        public DateTime? lastSeen { get; set; }
    }
    
    public class RootObject
    {
        public CidrData[] cidrs { get; set; }
    }
    
    class Program
    {
        static void Main()
        {
            var data = new RootObject
            {
                cidrs = new[]
                {
                    new CidrData
                    {
                        cidr = null,
                        failed = 1,
                        firstSeen = null,
                        lastSeen = null
                    }
                }
            };
    
            // Serialize the object to JSON with formatting
            string json = JsonConvert.SerializeObject(data, Formatting.Indented);
    
            Console.WriteLine(json);
        }
    }