我无法反序列化我的WCF Web服务的结果。该方法返回一个List<RecipeEntity>
,它被序列化为XML,如下所示。当我尝试反序列化时,我只是得到一个异常,如下所示。看来我无法反序列化<ArrayOfRecipe>
到List<RecipeEntity>
。请注意0由合同名称映射到Recipe
。将XML反序列化为<ArrayOf>以列表<>
搜索后,我看到很多人提出了XmlArray和XmlElement属性,但据我所知他们不适用于GetRecipes()
方法。我只看到它们用在序列化类的字段上。
我知道我可以将List<RecipeEntity>
包装在RecipeList
类中,然后返回,但是我宁愿直接反序列化到列表<>以获得任何给定的类型。
例外:
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);
}