如何序列化包含字典的类?
我有以下类:
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Dictionary<string, string> Attributes { get; set; }
}
我想使用 XmlSerializer 对其进行序列化并获得以下输出:
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Attributes>
<PhoneNumber>12345</PhoneNumber>
<StreetName>...</StreetName>
<StreetNumber>...</StreetNumber>
...
</Attributes>
</Person>
任何帮助将不胜感激。
I have the following class:
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Dictionary<string, string> Attributes { get; set; }
}
I would like to serialize it using XmlSerializer and get the following output:
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Attributes>
<PhoneNumber>12345</PhoneNumber>
<StreetName>...</StreetName>
<StreetNumber>...</StreetNumber>
...
</Attributes>
</Person>
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
与 MrFox 的答案类似,这是我过去使用过的一种方法,效果很好。
我凭记忆输入此内容,并没有尝试对其进行编译,因此可能存在一两个错误。但希望它能传达这个想法。此外,这还假设您的数据的值的键中不包含逗号或竖线。如果是这种情况,此解决方案可能不适合您。
Similar to MrFox's answer, this is a hack I've used in the past that works good enough.
I typed this up from memory and didn't try to compile it, so there may be a bug or two. But hopefully it gets the idea across. Also, this assumes that your data will not have a comma or a pipe in either the keys of the values. If that's the case, this solution may not work for you.
我以前做过这个:
I've done this before:
为什么不使用ProtocolBuffer来序列化。它是开源和免费的平台,您可以将它与 Java、C++ 和 Python 一起使用。这是一个小费。
Why don't you use ProtocolBuffer to serialize. It is opensource and free plataform, you can use it with Java, C++ and Python. It's a tip.
因为不可能在 dotnet 中序列化字典。我的解决方案是这样的:
输出:
核心代码
使用代码
As its not possible to serialize a dictionary in dotnet. My Solution is this:
Output:
Core Code
Usage Code