将窗体表单字段内容保存到JSON文件中

时间:2014-07-17 14:15:34

标签: c# json winforms


我有一个带有一些字段的窗体:

  • 两个 ListView InputFieldsOutputFields

  • 三个 TexBox Title1Title2Title3

  • 两个按钮Save To FileRead from File


我的问题:

当我点击Save To File按钮时,我想将两个ListViews和三个TextBox的所有内容保存到 JSON 文件中。< / p>

当我点击Read from File时,我想从 JSON 文件中填充ListViewsTextBoxs

了解:

我将Id保存在Tag的每个项目的ListView上。


我的JSON文件的结构:

{
    "title1": "example Title 1",
    "title2": "example Title 2",
    "title3": "example Title 3",

    "inputfields": {
        "item1": {
                    "name": "SGML",
                    "tag": "SGML"
                },
        "item2": {
                    "name": "SGML",
                    "tag": "SGML"
                },          
        ......

        "itemN": {
                    "name": "SGML",
                    "tag": "SGML"
                 }
           },

    "outputfields": {
        "item1": {
                    "name": "SGML",
                    "tag": "SGML"
                },
        "item2": {
                    "name": "SGML",
                    "tag": "SGML"
                },          
        ......

        "itemM": {
                    "name": "SGML",
                    "tag": "SGML"
                }
    }
}

有什么功能可以帮我吗?

感谢Stackoverflowers。

3 个答案:

答案 0 :(得分:2)

您可以使用一个包含场景背后数据的类,并使用像JSON.NET这样的库将此类序列化为Json并返回...

JSON.NET

答案 1 :(得分:1)

好的,这很简单。

您需要做的是首先创建一个名为Filed的对象,其中包含Item对象。然后Item对象有两个标签和名称属性。这样的事情。但请注意我还没有测试代码,我只是在记事本上写了它。但它应该是这样的。

导入此库:使用System.Web.Script.Serialization;

然后创建这个类:

    public class Field
{
    public Field(){}
    public Item item1{set; get;}
    public Item item2{set; get;}
    public Item item3{set; get;}

}

另一个名为item

的类
public class Item
    {
        public Item(){}
        public string name{set; get;}
        public string Tag{set; get;}

    }

然后是这样的:

List<Field> Items = new List<Field>{
                   new Field{item1 = new Item{name:title1.Text, Tag.Text}, item2 = new Item{name:title1.Text, Tag.Text}, item3 = new Item{name:title1.Text, Tag.Text}},
                   new Field{item2 = new Item{name:title1.Text, Tag.Text}, item2 = new Item{name:title1.Text, Tag.Text}, item3 = new Item{name:title1.Text, Tag.Text}},}
                   };


string jsonString = Items.ToJSON();

答案 2 :(得分:1)

肯定是可能的。最简单的方法是定义一个与JSON结构相对应的类,创建它的实例并用字段中的数据填充它,然后序列化该对象。

类似地,您可以从文件中加载&#39;功能。在这种情况下,您加载JSON,将其反序列化为对象,然后使用对象中的数据填充字段。

考虑到序列化/反序列化过程本身,您可以找到非常好的教程here或此处。