Tag Archive for serialization

De-serialize Base64 String to Object

public static object DeserializeBase64(string s)
{
// We need to know the exact length of the string - Base64 can sometimes pad us by a byte or two
int p = s.IndexOf(':');
int length = Convert.ToInt32(s.Substring(0, p));

// Extract data from the base 64 string!
byte[] memorydata = Convert.FromBase64String(s.Substring(p + 1));
MemoryStream rs = new MemoryStream(memorydata, 0, length);
BinaryFormatter sf = new BinaryFormatter();
object o = sf.Deserialize(rs);
return o;
}

source

Serialize Object to a Base64 String

public static string SerializeBase64(object o)
{
// Serialize to a base 64 string
byte[] bytes;
long length = 0;
MemoryStream ws = new MemoryStream();
BinaryFormatter sf = new BinaryFormatter();
sf.Serialize(ws, o);
length = ws.Length;
bytes = ws.GetBuffer();
string encodedData = bytes.Length + ":" + Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None);
return encodedData;
}

source

Serialization of Java object to AMF

package amfdemo;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import flex.messaging.io.SerializationContext;
import flex.messaging.io.amf.Amf3Input;
import flex.messaging.io.amf.Amf3Output;
import javax.xml.parsers.DocumentBuilderFactory;

public class AmfTest {

public static void main(String[] args) {
try {

SerializationContext context = getSerializationContext();

TestBean testBean = new TestBean();
testBean.setByte(new Byte((byte) 9));
testBean.setBigDecimal(new BigDecimal("9.9"));
testBean.setBoolean(new Boolean("true"));
testBean.setCharacter(new Character('c'));
testBean.setCalendar(Calendar.getInstance());
testBean.setDate(Calendar.getInstance().getTime());
testBean.setDouble(new Double(999.9));
testBean.setFloat(new Float(99.9f));
testBean.setInteger(new Integer("999"));
testBean.setList(new ArrayList());
testBean.setLong(new Long(99999));
testBean.setMap(new HashMap());
testBean.setDocument(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
testBean.setShort(new Short("99"));
testBean.setString("test");

ByteArrayOutputStream bout = new ByteArrayOutputStream();
Amf3Output amf3Output = new Amf3Output(context);
amf3Output.setOutputStream(bout);
amf3Output.writeObject(testBean);
amf3Output.flush();
amf3Output.close();

InputStream bIn = new ByteArrayInputStream(bout.toByteArray());
Amf3Input amf3Input = new Amf3Input(context);
amf3Input.setInputStream(bIn);
TestBean o = (TestBean) amf3Input.readObject();

System.out.println(o.getByte().equals(testBean.getByte()));
System.out.println(o.getBigDecimal().equals(testBean.getBigDecimal()));
System.out.println(o.getBoolean().equals(testBean.getBoolean()));
System.out.println(o.getCharacter().equals(testBean.getCharacter()));
System.out.println(o.getCalendar().equals(testBean.getCalendar()));
System.out.println(o.getDate().equals(testBean.getDate()));
System.out.println(o.getDouble().equals(testBean.getDouble()));
System.out.println(o.getFloat().equals(testBean.getFloat()));
System.out.println(o.getInteger().equals(testBean.getInteger()));
System.out.println(o.getLong().equals(testBean.getLong()));
System.out.println(o.getString().equals(testBean.getString()));

} catch (Exception e) {
e.printStackTrace();
}
}

public static SerializationContext getSerializationContext() {

//Threadlocal SerializationContent
SerializationContext serializationContext = SerializationContext.getSerializationContext();
serializationContext.enableSmallMessages = true;
serializationContext.instantiateTypes = true;
//use _remoteClass field
serializationContext.supportRemoteClass = true;
//false  Legacy Flex 1.5 behavior was to return a java.util.Collection for Array
//ture New Flex 2+ behavior is to return Object[] for AS3 Array
serializationContext.legacyCollection = false;

serializationContext.legacyMap = false;
//false Legacy flash.xml.XMLDocument Type
//true New E4X XML Type
serializationContext.legacyXMLDocument = false;

//determines whether the constructed Document is name-space aware
serializationContext.legacyXMLNamespaces = false;
serializationContext.legacyThrowable = false;
serializationContext.legacyBigNumbers = false;

serializationContext.restoreReferences = false;
serializationContext.logPropertyErrors = false;
serializationContext.ignorePropertyErrors = true;
return serializationContext;

/*
serializationContext.enableSmallMessages = serialization.getPropertyAsBoolean(ENABLE_SMALL_MESSAGES, true);
serializationContext.instantiateTypes = serialization.getPropertyAsBoolean(INSTANTIATE_TYPES, true);
serializationContext.supportRemoteClass = serialization.getPropertyAsBoolean(SUPPORT_REMOTE_CLASS, false);
serializationContext.legacyCollection = serialization.getPropertyAsBoolean(LEGACY_COLLECTION, false);
serializationContext.legacyMap = serialization.getPropertyAsBoolean(LEGACY_MAP, false);
serializationContext.legacyXMLDocument = serialization.getPropertyAsBoolean(LEGACY_XML, false);
serializationContext.legacyXMLNamespaces = serialization.getPropertyAsBoolean(LEGACY_XML_NAMESPACES, false);
serializationContext.legacyThrowable = serialization.getPropertyAsBoolean(LEGACY_THROWABLE, false);
serializationContext.legacyBigNumbers = serialization.getPropertyAsBoolean(LEGACY_BIG_NUMBERS, false);
boolean showStacktraces = serialization.getPropertyAsBoolean(SHOW_STACKTRACES, false);
if (showStacktraces && Log.isWarn())
log.warn("The " + SHOW_STACKTRACES + " configuration option is deprecated and non-functional. Please remove this from your configuration file.");
serializationContext.restoreReferences = serialization.getPropertyAsBoolean(RESTORE_REFERENCES, false);
serializationContext.logPropertyErrors = serialization.getPropertyAsBoolean(LOG_PROPERTY_ERRORS, false);
serializationContext.ignorePropertyErrors = serialization.getPropertyAsBoolean(IGNORE_PROPERTY_ERRORS, true);
*/
}
}

source

Action script to string serialization and de-serialization

package
{
import flash.utils.ByteArray;
import mx.utils.Base64Encoder;
import mx.utils.Base64Decoder;

public class SerializationUtils {
public static function serializeToString(value:Object):String{
if(value==null){
throw new Error("null isn't a legal serialization candidate");
}
var bytes:ByteArray = new ByteArray();
bytes.writeObject(value);
bytes.position = 0;
var be:Base64Encoder = new Base64Encoder();
be.encode(bytes.readUTFBytes(bytes.length));
return be.drain();
}

public static function readObjectFromStringBytes(value:String):Object{
var dec:Base64Decoder=new Base64Decoder();
dec.decode(value);
var result:ByteArray=dec.drain();
result.position=0;
return result.readObject();
}
}
}

source

Xml Config Entry to Write out Temporary Assemblies Created for the Serializers

<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="4"/>
</switches>
</system.diagnostics>

source

Xml Config Snippet For XMLSerializer Temporary Classes

<system.diagnostics>
<switches>
<add name="XmlSerialization.Compilation" value="4"/>
</switches>
</system.diagnostics>

source

Serializing and Deserializing a Class Created with XSD.Exe Using XML Strings

public static string SerializeToXmlString(object targetInstance)
{
string retVal = string.Empty;
TextWriter writer = new StringWriter();
XmlSerializer serializer = new XmlSerializer(targetInstance.GetType());
serializer.Serialize(writer, targetInstance);
retVal = writer.ToString();
return retVal;
}
public static object DeserializeFromXmlString(string objectXml, Type targetType)
{
object retVal = null;
XmlSerializer serializer = new XmlSerializer(targetType);
StringReader stringReader = new StringReader(objectXml);
XmlTextReader xmlReader = new XmlTextReader(StringReader);
retVal = serializer.Deserialize(xmlReader);
return retVal;
}

source

Get XML String Out of an Instance of a Class Generated from an XSD File by XSD.exe

TextWriter writer = new StringWriter();
XmlSerializer serializer = new XmlSerializer(myObject.GetType());
serializer.Serialize(writer, myObject);
return writer.ToString();

source

Object Serialization

namespace MyObjSerial
{
[Serializable()]    //Set this attribute to all the classes that want to serialize
public class Employee : ISerializable //derive your class from ISerializable
{
public int EmpId;
public string EmpName;

//Default constructor
public Employee()
{
EmpId = 0;
EmpName = null;
}
}

//Deserialization constructor.
public Employee(SerializationInfo info, StreamingContext ctxt)
{
//Get the values from info and assign them to the appropriate properties
EmpId = (int)info.GetValue("EmployeeId", typeof(int));
EmpName = (String)info.GetValue("EmployeeName", typeof(string));
}

//Serialization function.
public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
{
//You can use any custom name for your name-value pair. But make sure you
// read the values with the same name. For ex:- If you write EmpId as "EmployeeId"
// then you should read the same with "EmployeeId"
info.AddValue("EmployeeId", EmpId);
info.AddValue("EmployeeName", EmpName);
}
}

// Serialize Sample
Stream stream = File.Open("EmployeeInfo.osl", FileMode.Create);
BinaryFormatter bformatter = new BinaryFormatter();

Console.WriteLine("Writing Employee Information");
bformatter.Serialize(stream, mp);
stream.Close();

// Deserialize Sample
mp = null;

//Open the file written above and read values from it.
stream = File.Open("EmployeeInfo.osl", FileMode.Open);
bformatter = new BinaryFormatter();

Console.WriteLine("Reading Employee Information");
mp = (Employee)bformatter.Deserialize(stream);
stream.Close();

Console.WriteLine("Employee Id: {0}",mp.EmpId.ToString());
Console.WriteLine("Employee Name: {0}",mp.EmpName);

source