piehwa.blogg.se

Delphi serialize object to string
Delphi serialize object to string











delphi serialize object to string

Note that Ideone uses Mono to execute code: the actual Exception you would get using the Microsoft. Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject() that is defined in the derived type's base class. Regarding the accepted answer, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible scenarios, while using the latter one fails sometimes. To serialize an object: var userData = new UserData Using XML serialization adds unnecessary extra text rubbish to the output.įor the following class public class UserDataīetter solution is to use JSON serialization (one of the best is Json.NET).

delphi serialize object to string

I know this is not really an answer to the question, but based on the number of votes for the question and the accepted answer, I suspect the people are actually using the code to serialize an object to a string. Return JsonConvert.SerializeObject(toSerialize) Public static string SerializeJson(this T toSerialize) Return JsonConvert.DeserializeObject(toDeserialize) Public static T DeserializeJson(this string toDeserialize) Using (StringWriter textWriter = new StringWriter()) Public static string SerializeXml(this T toSerialize) Return (T)xmlSerializer.Deserialize(textReader) Using (StringReader textReader = new StringReader(toDeserialize)) XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)) Public static T DeserializeXml(this string toDeserialize) Serialize and Deserialize XML/JSON ( SerializationHelper.cs): using Newtonsoft.Json NET runtime has a different Message than the one shown on Ideone, but it fails just the same. Īlso, Ideone uses Mono to execute code the actual Exception you would get using the Microsoft. Here is a link with some example code that motivate this statement, with XmlSerializer throwing an Exception when typeof(T) is used, because you pass an instance of a derived type to a method that calls SerializeObject that is defined in the derived type's base class. Note, it is important to use toSerialize.GetType() instead of typeof(T) in XmlSerializer constructor: if you use the first one the code covers all possible subclasses of T (which are valid for the method), while using the latter one will fail when passing a type derived from T. XmlSerializer.Serialize(textWriter, toSerialize) Using(StringWriter textWriter = new StringWriter()) XmlSerializer xmlSerializer = new XmlSerializer(toSerialize.GetType()) Use a StringWriter instead of a StreamWriter: public static string SerializeObject(this T toSerialize)













Delphi serialize object to string