我有以下两个功能:
public static string Serialize(object obj)
{
DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.GetBuffer());
}
public static object Deserialize(string xml, Type toType)
{
MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml));
// memoryStream.Position = 0L;
XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
DataContractSerializer dataContractSerializer = new DataContractSerializer(toType);
return dataContractSerializer.ReadObject(reader);
}
Run Code Online (Sandbox Code Playgroud)
第一个似乎将对象序列化为xml字符串就好了.XML显示有效,没有损坏的标记,开头或结尾没有空格等.现在第二个函数不希望将我的xml字符串反序列化回对象.在最后一行我得到:
反序列化[MY OBJECT TYPE HERE]类型的对象时出错.根级别的数据无效.第1行,第1位.
我究竟做错了什么?我尝试重写Deserialize函数几次,它似乎总是出现同样的错误.谢谢!
哦,这就是我调用2个函数的方式:
SomeObject so = new SomeObject();
string temp = SerializationManager.Serialize(so);
so = (SomeObject)SerializationManager.Deserialize(temp, typeof(SomeObject));
Run Code Online (Sandbox Code Playgroud) 我想将以下 XML 文档发送到我的 Web Api 2 控制器;但是,该[FromBody]参数始终为空。
这是请求 XML 正文:
<razorInbound server="PortfolioExposureServer" request="lookupRiskPointRecord">
<caller>RazorClient</caller>
<responseMode>xml</responseMode>
<body>
<conditions>
<fromOffset>0</fromOffset>
<top>100</top>
<condition>
<keyPath>
<keyElement nodeOffset='1'>Currency</keyElement>
<keyElement nodeOffset='2'>ID</keyElement>
</keyPath>
<lookupValue>USD</lookupValue>
</condition>
</conditions>
</body>
</razorInbound>Run Code Online (Sandbox Code Playgroud)
使用Postman发送请求,如下:
POST /api/razorXmlRequest HTTP/1.1
Host: localhost:5000
Content-Type: application/xml
Cache-Control: no-cache
Postman-Token: 6ca91ebf-31e0-77f2-6f81-cb9993b69b1a
<razorInbound server="PortfolioExposureServer" request="lookupRiskPointRecord">
<caller>RazorClient</caller>
<responseMode>xml</responseMode>
<body>
<conditions>
<fromOffset>0</fromOffset>
<top>100</top>
<condition>
<keyPath>
<keyElement nodeOffset='1'>Currency</keyElement>
<keyElement nodeOffset='2'>ID</keyElement>
</keyPath>
<lookupValue>USD</lookupValue>
</condition>
</conditions>
</body>
</razorInbound>Run Code Online (Sandbox Code Playgroud)
和 Web Api 2 控制器:
注意:该param参数始终为null
我相信我需要一个正确的类定义来正确映射 XML 请求,但我不确定如何构造它。
using System; …Run Code Online (Sandbox Code Playgroud)