JSON格式写入文件

本文关键字:文件 格式 JSON | 更新日期: 2023-09-27 18:22:02

我想用JSON格式写我的项目,但我的文件是空的。这是我的两个班:

public class DocPart
{
    public string Title { get; set; }
    public bool Checked { get; set; }
}
public class DocConfig
{
    public List<DocPart> Parts { get; set; }
    public static DocConfig LoadFromString(string jsonData)
    {
        var config = new DocConfig();
        config.Parts = new List<DocPart>();
        var part = new DocPart
        {
            Title = "chapter1",
            "chapter2",
            Checked = checkBox1.Checked,
            checkbox2.Checked
        };
        config.Parts.Add(part);
        var configString = config.SaveToString();
        File.WriteAllText(@"C:'link to my file", configString);
        var configString = File.ReadAllText(@"C:'link to my file");
        var config = DocConfig.LoadFromString(configString);
        foreach (var part in config.Parts)
        {
            if (part.Title == "chapter1")
                chekbox1.Checked = part.Checked;
            if (part.Title == "chapter2")
                checkbox2.Checked = part.Checked;
            var serializer = new DataContractJsonSerializer(typeof(DocConfig));

            var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
            var config = (DocConfig)serializer.ReadObject(ms);

            return config;
        }
    }

    public string SaveToString()
    {
        var serializer = new DataContractJsonSerializer(typeof(DocConfig));
        var ms = new MemoryStream();
        serializer.WriteObject(ms, this);
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}

所以我运行我的程序,一切看起来都很正常,但我的文件仍然是空的,没有任何JSON格式的数据。也许你能帮我?

谢谢。

JSON格式写入文件

public class DocPart
{
    public string Title { get; set; }
    public bool Checked { get; set; }
}
public class DocConfig
{
    public List<DocPart> Parts { get; set; }
    public static DocConfig LoadFromString()
    {
        var config = new DocConfig();
        config.Parts = new List<DocPart>();
        var part1 = new DocPart
        {
            Title = "chapter1",
            Checked = checkBox1.Checked
        };
        config.Parts.Add(part1);
        var part2 = new DocPart
        {
            Title = "chapter2",
            Checked = checkBox2.Checked
        };
        config.Parts.Add(part2);
        var configString = config.SaveToString();
        File.WriteAllText(@"d:'temp'test.json", configString);
        configString = File.ReadAllText(@"d:'temp'test.json"); 
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(configString));
        var serializer = new DataContractJsonSerializer(typeof(DocConfig));
        config = (DocConfig)serializer.ReadObject(ms);
        foreach (var part in config.Parts)
        {
            if (part.Title == "chapter1")
            {
                chekbox1.Checked = part.Checked;
                Debug.WriteLine("chapter1" + part.Checked);
            }
            if (part.Title == "chapter2")
            {
                checkbox2.Checked = part.Checked;
                Debug.WriteLine("chapter2" + part.Checked);
            }
        }
        return config;
    } 

    public string SaveToString()
    {
        var serializer = new DataContractJsonSerializer(typeof(DocConfig));
        var ms = new MemoryStream();
        serializer.WriteObject(ms, this);
        return Encoding.UTF8.GetString(ms.ToArray());
    }
}

下面是我为您模拟的一个非常简单的例子。。。

void Main()
{
    const string filePath = @"C:'FilePath'json.txt";
    const string testJson = @"{""glossary"": {""title"": ""example glossary"",      ""GlossDiv"": {""title"": ""S"",            ""GlossList"": {""GlossEntry"": {""ID"": ""SGML"",                  ""SortAs"": ""SGML"",                   ""GlossTerm"": ""Standard Generalized Markup Language"",                    ""Acronym"": ""SGML"",                  ""Abbrev"": ""ISO 8879:1986"",                  ""GlossDef"": {""para"": ""A meta-markup language, used to create markup languages such as DocBook."",                      ""GlossSeeAlso"": [""GML"", ""XML""]},                  ""GlossSee"": ""markup""}}}}}";
    // Now we have our Json Object...
    SampleJson sample = JsonConvert.DeserializeObject<SampleJson>(testJson);
    // We convert it back into a string with indentation...
    string jsonString = JsonConvert.SerializeObject(sample, Newtonsoft.Json.Formatting.Indented);
    // Now simply save to file...
    using (StreamWriter writer = new StreamWriter(filePath))
    {
        writer.WriteLine(jsonString);
    }
    Process.Start(filePath);
}
// The following classes are what the `testJson` string is deserialized into.
public class GlossDef
{
    [JsonProperty("para")]
    public string Para { get; set; }
    [JsonProperty("GlossSeeAlso")]
    public string[] GlossSeeAlso { get; set; }
}
public class GlossEntry
{
    [JsonProperty("ID")]
    public string ID { get; set; }
    [JsonProperty("SortAs")]
    public string SortAs { get; set; }
    [JsonProperty("GlossTerm")]
    public string GlossTerm { get; set; }
    [JsonProperty("Acronym")]
    public string Acronym { get; set; }
    [JsonProperty("Abbrev")]
    public string Abbrev { get; set; }
    [JsonProperty("GlossDef")]
    public GlossDef GlossDef { get; set; }
    [JsonProperty("GlossSee")]
    public string GlossSee { get; set; }
}
public class GlossList
{
    [JsonProperty("GlossEntry")]
    public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("GlossList")]
    public GlossList GlossList { get; set; }
}
public class Glossary
{
    [JsonProperty("title")]
    public string Title { get; set; }
    [JsonProperty("GlossDiv")]
    public GlossDiv GlossDiv { get; set; }
}
public class SampleJson
{
    [JsonProperty("glossary")]
    public Glossary Glossary { get; set; }
}