我有一个带有一些字段的窗体:
两个 ListView (InputFields
和OutputFields
)
三个 TexBox (Title1
,Title2
和Title3
)
两个按钮(Save To File
和Read from File
)
当我点击Save To File
按钮时,我想将两个ListViews
和三个TextBox
的所有内容保存到 JSON 文件中。< / p>
当我点击Read from File
时,我想从 JSON 文件中填充ListViews
和TextBoxs
。
了解:
我将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。
答案 0 :(得分:2)
您可以使用一个包含场景背后数据的类,并使用像JSON.NET这样的库将此类序列化为Json并返回...
答案 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或此处。