我在反序列化WCF webservice的结果时遇到了问题。该方法返回一个
在搜索后,我发现许多人提出了XmlArray和XmlElement属性,但据我所知,它们不适用于
我知道我可以将
异常:
反序列化代码:
List<RecipeEntity>
,并被序列化为以下显示的XML。当我尝试反序列化时,我只得到了下面显示的异常。似乎我不能将<ArrayOfRecipe>
反序列化为List<RecipeEntity>
。请注意,RecipeEntity
按合同名称映射到Recipe
。在搜索后,我发现许多人提出了XmlArray和XmlElement属性,但据我所知,它们不适用于
GetRecipes()
方法。我只看到它们用于序列化类的字段。我知道我可以将
List<RecipeEntity>
封装在一个RecipeList
类中并返回,但我更愿意直接将任何给定类型的对象反序列化为List<>。异常:
System.InvalidOperationException was caught
Message=There is an error in XML document (1, 2).
StackTrace:
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, Object events)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle)
at System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader)
at GroceriesAppSL.Pages.Home.GetRecipesCallback(RestResponse response)
InnerException: System.InvalidOperationException
Message=<ArrayOfRecipe xmlns='Groceries.Entities'> was not expected.
StackTrace:
at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderList1.Read5_Recipe()
InnerException:
数据契约:
[DataContract(Name = "Recipe", Namespace = "Groceries.Entities")]
public class RecipeEntity
{
[DataMember] public int Id;
[DataMember] public string Name;
[DataMember] public string Description;
}
实现:
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, UriTemplate = "Recipes/{username}")]
List<RecipeEntity> GetRecipes(string username);
}
public class MyService : IMyService
{
public List<RecipeEntity> GetRecipes(string username)
{
return _recipeDB.Recipes.Select(ToEntity).ToList();
}
}
示例XML结果,仅供说明目的。
<ArrayOfRecipe xmlns="Groceries.Entities" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Recipe>
<Id>139</Id>
<Name>ExampleRecipe</Name>
<Description>5 L milk;4 eggs</Description>
</Recipe>
<Recipe>...</Recipe>
<Recipe>...</Recipe>
<Recipe>...</Recipe>
...
</ArrayOfRecipe>
反序列化代码:
using (var xmlReader = XmlReader.Create(new StringReader(response.Content)))
{
var xs = new System.Xml.Serialization.XmlSerializer(typeof(List<RecipeEntity>));
var recipes = (List<RecipeEntity>)xs.Deserialize(xmlReader);
}