簡體   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