Tôi gặp khó khăn khi deserializing kết quả từ webservice WCF của tôi. Phương thức trả về một List<RecipeEntity>
, được tuần tự hóa thành XML như được hiển thị bên dưới. Khi tôi cố gắng deserialize tôi chỉ nhận được một ngoại lệ, được hiển thị dưới đây. Có vẻ như tôi không thể deserialize <ArrayOfRecipe>
đến List<RecipeEntity>
. Lưu ý rằng RecipeEntity
được ánh xạ theo tên hợp đồng thành Recipe
.Deserialize <ArrayOf> trong XML vào Danh sách <>
Sau khi tìm kiếm, tôi thấy nhiều đề xuất thuộc tính XmlArray và XmlElement, nhưng theo như tôi có thể nói chúng không áp dụng ở đây theo phương pháp GetRecipes()
. Tôi chỉ thấy chúng được sử dụng trên các lĩnh vực của các lớp serialized.
Tôi biết tôi có thể quấn List<RecipeEntity>
trong lớp RecipeList
và trả lại thay vào đó, nhưng tôi muốn deserialize trực tiếp vào Danh sách <> cho bất kỳ loại nhất định nào.
Ngoại lệ:
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:
hợp đồng dữ liệu:
[DataContract(Name = "Recipe", Namespace = "Groceries.Entities")]
public class RecipeEntity
{
[DataMember] public int Id;
[DataMember] public string Name;
[DataMember] public string Description;
}
Thực hiện:
[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();
}
}
Kết quả mẫu XML, chỉ mang tính chất minh họa.
<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>
đang Deserialization:
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);
}