繁体   English   中英

如何将列表框项目保存到 JSON 文件中?

[英]How do I save list box items into JSON file?

我有一个动态填充的列表框。 我在项目文件夹中创建了一个 sample.json 文件,并希望以简单的string[]格式保存保存到 samepl.json 中的所有列表框项目。

private void btnSave_Click(object sender, EventArgs e)
{
    foreach (var item in listBox1.Items)
    {
         json = JsonConvert.SerializeObject(item.ToString());
    }
}

sample.json
[]

使用Json.net,您可以创建一个JArray并使用Add方法,这样您就可以从列表框中添加元素。

完成后,您可以使用方法string json = ToString(Formatting)来获得整齐缩进的 JSON

调用 ToString() 后,您可以使用 System.IO.File 的静态方法保存到文件:

File.WriteAllText(json, path);

下面是一些示例代码,显示了如何从 ListBox 项创建 Json 字符串,然后将该字符串写入文件。 然后展示了如何读回该代码并使用原始数据重新填充 ListBox 项。

为了能够使用 JavaScriptSerializer,您必须向您的项目添加对 System.Web.Extensions 的引用。 您可以通过单击 Project -> Add Reference... -> 选择“Framework”,然后选择“Assemblies”,然后选中“System.Web.Extensions”框并单击“确定”来完成此操作。

        // Create an example ListBox
        System.Windows.Forms.ListBox lb = new System.Windows.Forms.ListBox();
        // Add some random items to the list box
        lb.Items.Add("123");
        lb.Items.Add(456);
        lb.Items.Add(false);
        // Create a new JavaScriptSerializer to convert our object to and from a json string
        JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        // Use the JavaScriptSerializer to convert the ListBox items into a Json string
        string writeJson = jss.Serialize(lb.Items);
        // Write this string to file
        File.WriteAllText("ListBoxItems.json", writeJson);
        // Clear all element from the ListBox
        lb.Items.Clear();
        // Read the json string back from the file
        string readJson = File.ReadAllText("ListBoxItems.json");
        // Use the JavaScriptSerializer Deserialize method to add the objects back into the ListBox item collection.
        lb.Items.AddRange(jss.Deserialize<object[]>(readJson));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM