c# .net 6 JSON 使用转义符和 qouble 引用开始和结束来保存

问题描述 投票:0回答:1

我一生都无法弄清楚为什么正确的 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 字符串。

尝试将字符串加载到新的字符串变量中,然后写入该新字符串。 将虚拟数据直接发送到双引号内的方法,显示与上述相同,但使用双引号和转义符写入。

c# json io
1个回答
0
投票

您必须序列化对象而不是字符串。 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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.