When we work with the basket in commerce, storing multiple custom objects against a line item can be tricky. We can extend line item to have as many custom single properties as you require, but we do not have the option to create new arrays or lists against a line item. In today's tutorial I am going to discuss how to get around this limitation.
Extending LineItem
I have previously written about how to extend the LineItem class in this article Adding Custom MetaData to the LineItem Class in Episerver Commerce via Code and Adding Custom MetaData to the Cart Class in Episerver Commerce via Code
The first thing you will need to do is create a custom property against the LineItem class or the class. Where you store your custom objects is up to you and will probably be dictated by your requirements. In this tutorial I'm going to assume you've done that bit and we'll be working with a custom property already set-up on the Cart, so I'll skip the code.
Json.Net
A very quick and easy win to serialise data is to use Json.Net. Json.Net provides the methods where you basically define the.NET object type you want to convert and the API does the rest for you... it really is that simple. More information about the Json.Net serialisation and deserialization can be found here. For this little demo, we will use a custom object I've randomly created, which looks like this:
Serialising
The first part of this process is storing your custom .NET objects in the cart. In the method above, we pass in the cart and the objects we want to work with, use JsonConvert to serialise it and then access a customer property on Cart (I'm assuming you have already set this up using the links above) and storing it.
The cart needs to be saved. I'm currently using the new commerce Order Repository to load and save my cart but as it is still in beta, the majority of readers won't be using it. This is the only reason why I have omitted the save code from this snippet BUT you will need to save it if you want it persisted to the database.
Deserializing Vouchers
Next up is getting the data from the cart when you need it. We will still need the Episerver cart. The first thing we do is get the serialised data we stored in SerializeVouchersToCart, we then user JsonConvert.DeserializeObject to get the objects back out of the cart.
Conclusion
Today's tutorial was quite basic but very useful if you need to work with custom objects and your Episerver Cart or line item. Instead of being stuck with single properties, we can use Json.Net to serialise/deserialize objects. This allows us to store lists of objects which can be extremely useful. One word of caution though, you need to consider how many objects you will be storing. As you'll be serialising objects in a single field, there will be a maximum amount of data you can store.