Skip to main content
Published: September 30 2005, 12:00:00 AMUpdated: July 25 2022, 2:48:39 AM

How do I serialize objects such as the Item object in the .NET SDK?

The C# code below makes the GetCategories call using the .NET SDK and then proceeds to serialize the results into a file, and then deserialize back into an object.
The XMLSerializer class in the .NET Framework is used.

In the source code, you will have to put in your own DevID, AppID, CertID and eBayToken information for the Sandbox and make sure the reference to eBay.Service.dll is valid before building the project and running it (note that the existing reference to eBay.Service.dll has the default path C:\Program Files\eBay\eBay .NET SDK v<version> Full Release\eBay.Service.dll)

Note that this code will create a 25MB file named categories.xml in the Debug folder where the exe is run from.

using System;
using eBay.Service.Core.Sdk;
using eBay.Service.Core.Soap;
using eBay.Service.Call;
using System.Xml.Serialization;
using System.IO;

...

ApiContext oContext = new ApiContext();
oContext.ApiCredential.ApiAccount.Developer = "xxx";
oContext.ApiCredential.ApiAccount.Application = "xxx";
oContext.ApiCredential.ApiAccount.Certificate = "xxx";
oContext.ApiCredential.eBayToken = "xxx";
oContext.SoapApiServerUrl = "https://api.sandbox.ebay.com/wsapi";
oContext.Site = eBay.Service.Core.Soap.SiteCodeType.US;

GetCategoriesCall oGetCategoriesCall = new GetCategoriesCall(oContext);
oGetCategoriesCall.Site = oContext.Site;
oGetCategoriesCall.ViewAllNodes = true;
oGetCategoriesCall.DetailLevelList.Add(DetailLevelCodeType.ReturnAll);
oGetCategoriesCall.EnableCompression = false;

CategoryTypeCollection oCategoriesCollection = oGetCategoriesCall.GetCategories();

// Create an instance of the XmlSerializer class
// specify the type of object to serialize.
XmlSerializer oSerializer = new XmlSerializer(typeof(CategoryTypeCollection));
TextWriter oWriter = new StreamWriter("categories.xml");

// Serialize the category collection, and close the TextWriter.
oSerializer.Serialize(oWriter, oCategoriesCollection);
oWriter.Close();

// Create an instance of the XmlSerializer class
// specify the type of object to be deserialized.
XmlSerializer oDeSerializer = new XmlSerializer(typeof(CategoryTypeCollection));

// A FileStream is needed to read the XML document.
FileStream oFileStream = new FileStream("categories.xml", FileMode.Open);
// Declare an object variable of the type to be deserialized.
CategoryTypeCollection oCategoriesCollectionFromFile;
/* Use the Deserialize method to restore the object's state with data from the XML document. */
oCategoriesCollectionFromFile = (CategoryTypeCollection) oDeSerializer.Deserialize(oFileStream);

// oCategoriesCollectionFromFile will be identical to oCategoriesCollection

How well did this answer your question?
Answers others found helpful