Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize an IList<T>?

I've got an OR mapper (iBatis.Net) that returns an IList.

// IList<T> QueryForList<T>(string statementName, object parameterObject);
var data = mapper.QueryForList<Something>(statement, parameters);

I'm trying to use it in an webservice an want to return the data 1:1. Of course I can't return IList in a WebMethod, because it is an interface and therefore not serializable.

I found that the mapper is really returning an List. But I'm afraid to cast it to List because of course the mappers inner workings could change in future versions (and it just feels dirty).

So should I ...

a) return new List<Something>(data);

b) return (List<Something>)data;

c) // your solution here

Thanks a lot!

like image 677
Hinek Avatar asked Jan 21 '09 09:01

Hinek


People also ask

Can you serialize a list?

A List can be serialized—here we serialize (to a file) a List of objects. Serialize notes. The next time the program runs, we get this List straight from the disk. We see an example of BinaryFormatter and its Serialize methods.

How do you make a function serializable in Scala?

To make a Scala class serializable, extend the Serializable trait and add the @SerialVersionUID annotation to the class: @SerialVersionUID(100L) class Stock(var symbol: String, var price: BigDecimal) extends Serializable { // code here ... }

What is serialize XML?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.


2 Answers

If it really is a List<T> but you want to protect against change and have it still work, then the most performant solution will be to attempt to cast it to a list, and if that fails then create a new list from its content, e.g.

var data = mapper.QueryForList<T>(statement, parameters);
var list = data as List<T> ?? new List<T>(data);

However, you mention that you can't return an interface because it's a web service. This may have been true with ASMX and the XmlSerializer class, but if you build the web service using WCF and use the DataContractSerializer then it will happily serialize collection interfaces (both as inputs to and outputs from the service). That type of change may be somewhat larger than you're looking for though!

like image 179
Greg Beech Avatar answered Sep 19 '22 17:09

Greg Beech


Why should you serialize IList :) Just use it as a source for your own collection and serialize it:

var data = mapper.QueryForList<T>(statement, parameters);
var yourList = new List<T>(data);
//Serialize yourList here ))
like image 20
ProfyTroll Avatar answered Sep 20 '22 17:09

ProfyTroll