c# .net 6 JSON保存与escape和qouble引号开始和结束

kiayqfof  于 5个月前  发布在  C#
关注(0)|答案(1)|浏览(73)

对于我的生活,我不明白为什么一个序列化的正确的json字符串是保存与qouble引号和转义。
示例数据:发送到序列化程序的字符串变量:

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

字符串
从字符串变量保存:

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


示例方法写入文件:

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


就是这样,超级基本,但由于某种原因破坏了保存的JSON字符串。
尝试将字符串加载到一个新的字符串变量中,然后写入该新字符串。将伪数据直接发送到双引号内的方法,显示与上述相同,但写入时使用双引号并转义。

pgccezyw

pgccezyw1#

序列化对象而不是字符串,JSON字符串序列化没有意义,可以直接输出到stream,对象序列化示例:

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

字符串

相关问题