【发布时间】:2013-03-05 18:45:20
【问题描述】:
我曾经将控制信息存储在一个 XML 文件中,如下所示:
<Controls>
<Label Id="heading" Text="This is a heading!" FontStyle="(FontStyleDataHere)" Location="20, 10" />
<Label Id="bodyText" Text="This is Body text." FontStyle="(FontStyleDataHere)" Location="20, 70" />
</Controls>
我一直在寻找我去年拥有的多页代码的打印版本,这是我留下的唯一备份,现在找不到。
因为我不记得我到底是怎么做到的,所以我总是觉得 XML 非常乏味。所以我想,为什么不试试 JSON。好像轻松了一点……
现在,根据上面的代码,我可以创建一个 Person 类型的类,并序列化对象并将其写入文件(或控制台 - 随便):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
namespace SerializeToJson
{
class Program
{
[DataContract]
internal class Person
{
[DataMember]
internal String Name;
[DataMember]
internal Int32 Age;
}
static void Main(string[] args)
{
Person person = new Person()
{
Name = "Jason rules.",
Age = 19
};
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
serializer.WriteObject(stream, person);
stream.Position = 0;
StreamReader reader = new StreamReader(stream);
Console.Write("Json form of Person object: ");
Console.WriteLine(reader.ReadToEnd());
Console.ReadKey();
}
}
}
但问题是,我不知道如何将控件序列化为 Json。这是我真正需要的。而且,很明显,我需要在稍后的时间点反序列化它们,以便可以在运行时重新创建它们。
这可以用 JSON 来完成,还是建议我仍然使用 XML?
【问题讨论】:
-
请问您需要这个做什么?
-
我有一个应用程序,它允许其用户根据自己的喜好重新排列整个用户界面,所以这就是为什么我需要将控制信息和状态保存到文件并能够再次检索它的原因。跨度>