我有一个动态填充的列表框。
我在项目文件夹中创建了一个sample.json文件,并希望将所有保存在samepl.json中的列表框项目保存在简单$('#colour input, #shape input').on('change', function(){
$('#container .item').hide();
var colour = $('#colour input:checked').val() ? '.' + $('#colour input:checked').val() : '',
shape = $('#shape input:checked').val() ? '.' + $('#shape input:checked').val() : '';
$('#container .item' + colour + shape).show();
});
中
格式。
string[]
答案 0 :(得分:1)
使用Json.net,您可以创建JArray
并使用方法Add
,这样您就可以添加列表框中的元素。
完成此操作后,您可以使用method string json = ToString(Formatting)
整齐地缩进JSON
调用ToString()后,您可以使用System.IO.File的静态方法保存到文件:
File.WriteAllText(json, path);
答案 1 :(得分:1)
下面是一些示例代码,显示如何从ListBox项创建Json字符串,然后将该字符串写入file。然后显示如何重新读取该代码并使用原始数据重新填充ListBox项目。
为了能够使用JavaScriptSerializer,您必须向项目添加对System.Web.Extensions的引用。您可以通过单击项目 - >来完成此操作。添加参考... - >选择'框架'然后' 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));