JSON格式写入文件

时间:2015-11-16 13:36:24

标签: c# json file

我想用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格式数据。也许你可以帮助我?

感谢。

2 个答案:

答案 0 :(得分:0)

这是我为你嘲笑的一个非常简单的例子......

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

答案 1 :(得分:0)

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

}