Serializing to XML ArrayList<T> in .NET Core 3

旧街凉风 提交于 2019-12-12 23:04:13

问题


Is there a way to serialize ActionResult<ArrayList> from a controller in .net core 3, where ArrayList is composed of some type T (Person in this case).

It won't serialize to XML, only JSON. It complains the type Person is not known (even though it is, and it serializes just fine itself or as an array).

i.e. this fails serialization:

[HttpGet("List")]
public ActionResult<ArrayList> AllPersons() {...}

this works:

[HttpGet("List")]
public ActionResult<Person[]> AllPersons() {...}

So the Person type (T) can serialize just fine by itself, and Person[] also serializes just fine, but when an ArrayList (of Person) fails XML serialization with:

System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidOperationException: The type SimpleRESTServer.Models.Person was not expected. Use the XmlInclude or SoapInclude attribute to specify types that are not known statically.

(Person type is known statically, and both Person and Person[] will serialize just fine):

[XmlInclude(typeof(Person))]
[Serializable]
public class Person ...

回答1:


ArrayList has been deprecated for quite a while. As @MindingData mentioned in a comment, ArrayList isn't generic.

You should look into using List<Person> instead of ArrayList. I haven't seen ArrayList used in probably about a decade--chances are most serialization frameworks aren't going to handle it gracefully, at least in part because it implements neither IEnumerable<T> nor ICollection<T>. Migrating to newer, generic collection types will probably resolve any strange errors you encounter while dealing with older, deprecated, non-generic collection types.

You may be able to test this theory by using object[] instead of Person[] in your test case. ArrayList is closer to object[], whereas List<Person> is closer to Person[]. (That being said, some serialization frameworks will handle object[] correctly even when they're unable to handle ArrayList, so this isn't a perfect test.)



来源:https://stackoverflow.com/questions/57650085/serializing-to-xml-arraylistt-in-net-core-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!