Serializing and deserializing a ArrayList

Hello!

I am trying to serialize and deserialize a arraylist of objects. This object is called Pager and is defined as follows:

    public class Pager
    {
        public int ID { get; set; }
        public int RIC { get; set; }
        public string Name { get; set; }
        public string SerialNumber { get; set; }
    }

In a different class, I have made an Arraylist containing these Pagers.
I want to be able to save this list of pagers to my SD card as a JSON file and then read it back again.

I have been able to serialize the arraylist correctly by doing this:

var result = JsonConverter.Serialize(Pagers.ToArray()).ToString();

Now, however when I try to deserialize by running below code:

var bson = JsonConverter.Deserialize(result).ToBson();

Pager[] pagers = (Pager[]) JsonConverter.FromBson(bson, typeof(Pager[]));

I get this error:

#### Exception System.NullReferenceException - CLR_E_NULL_REFERENCE (1) ####
#### Message: 
#### GHIElectronics.TinyCLR.Data.Json.JsonConverter::PopulateObject [IP: 0013] ####
#### GHIElectronics.TinyCLR.Data.Json.JsonConverter::PopulateObject [IP: 036d] ####
#### GHIElectronics.TinyCLR.Data.Json.JsonConverter::FromBson [IP: 000d] ####
#### PagerServerV3._0.Files.PagerFile::AddPager [IP: 0032] ####
#### PagerServerV3._0.Program::Main [IP: 006a] ####
 Exception thrown: 'System.NullReferenceException' in GHIElectronics.TinyCLR.Data.Json.dll
An unhandled exception of type 'System.NullReferenceException' occurred in 
 GHIElectronics.TinyCLR.Data.Json.dll

I don’t know of a different way of deserializing my data. What am I doing wrong?

Also, is it possible to use something else than an arraylist? E.g. a normal C# list for example.

I would really appreciate if someone could help me out here.

https://docs.ghielectronics.com/software/tinyclr/tutorials/serialization.html

Thank you for your reply, but if you look at the code in the tutorial you sent and at mine, you see that they are practically the same.

I followed that tutorial, it’s what got me here in the first place.

Convert byte[] to string with Encoding.UTF8.GetBytes() and use DeserializeObject()

ToBson() FromBson() didnt work for me either.

public static byte[] Serialize(object data)
            {
                JToken json = JsonConverter.Serialize(data);
                string jsonString = json.ToString();
                byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);
                return jsonBytes;
            }

    public static Pager Deserialize(byte[] data)
            {
                if (data.Length > 0)
                {
                    string byteString = Encoding.UTF8.GetString(data);
                    Pager pager = (Pager)JsonConverter.DeserializeObject(byteString, typeof(Pager));
                    return pager;
                }
                return null;
            }
1 Like

Thank you! With this code I was able to solve my problem.