在 Serialized 类中序列化 RSAKeyValue 属性
我的 C# 项目中有一个类标有 [Serialized]
属性。它具有类型为 RSAKeyValue 类型的属性
:
[XmlElement(PUBLIC_KEY_TAG_NAME)]
public RSAKeyValue Key { get; private set; }
当我尝试将类的实例序列化为 XML,然后将该 XML 反序列化回类的实例时,我得到:
System.InvalidOperationException:System.Security.Cryptography.KeySizes 无法序列化,因为它没有无参数构造函数。
当我调用 XmlSerializer.Serialize
时会发生这种情况。我确定这是因为我的类中的 RSAKeyValue 属性,因为序列化的所有其他属性都是简单字符串。对此我能做什么?我是否应该围绕正确序列化/反序列化的 RSAKeyValue 实例创建自己的包装类?
以下是一些可以反序列化为 RSAKeyValue
实例的示例 XML:
<RSAKeyValue>
<Modulus>long string here...</Modulus>
<Exponent>short string here</Exponent>
</RSAKeyValue>
I have a class in my C# project marked with the [Serializable]
attribute. It has a property of type RSAKeyValue
:
[XmlElement(PUBLIC_KEY_TAG_NAME)]
public RSAKeyValue Key { get; private set; }
When I try to serialize an instance of my class to XML and then deserialize that XML back to an instance of my class, I get:
System.InvalidOperationException: System.Security.Cryptography.KeySizes cannot be serialized because it does not have a parameterless constructor.
This occurs when I call XmlSerializer.Serialize
. I'm sure it's because of the RSAKeyValue
property in my class since all the other properties that get serialized are simple strings. What can I do about this? Should I maybe make my own wrapper class around an RSAKeyValue
instance that properly serializes/deserializes?
Here is some sample XML that could be deserialized into an RSAKeyValue
instance:
<RSAKeyValue>
<Modulus>long string here...</Modulus>
<Exponent>short string here</Exponent>
</RSAKeyValue>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,XML Serializer 会忽略
[Serializable]
属性。其次,如果该类没有默认构造函数,则无法使用 XML 序列化程序对其进行序列化。
你想实现什么目标?也许您可以使用数据契约序列化器完成同样的事情?
创建一个仅包含模数和指数的类。从 RSAKeyValue 填充该类。序列化您的自定义类。反序列化后,用它创建一个新的RSAKeyValue。
First of all, the XML Serializer ignores the
[Serializable]
attribute.Second, if the class does not have a default constructor, then you can't serialize it using the XML Serializer, period.
What are you trying to accomplish? Perhaps you can accomplish the same thing using the Data Contract Serializer?
Create a class that contains just a Modulus and an Exponent. Fill that class from an RSAKeyValue. Serialize your custom class. After deserializing, use it to create a new RSAKeyValue.