Struct/Class to byte array and back again. How to do this?

I have a struct/class with configuration data that I want to store in an EEPROM and also read it back out on power up.

How can I convert the structure to a byte array and back again? All of the stuff in a search is for the old NETMF solutions.

Do you absolutely need to use a struct?
If NOT you can use a class and use json serializer to convert to byte and back.

I just edited my post. I can convert the struct easily to a class.

Is there any sample for how to use the json serialiser?

This works, the docs version does not work…
but read that anyway to know what nugets you need

 public class Device
        public int Id { get; set; }
        public string Name { get; set; }
        public string Ssid { get; set; }
        public string Password { get; set; }
        public string ApiUrl { get; set; }
        public bool IsTestLedOn { get; set; }

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 Device Deserialize(byte[] data)
            if (data.Length > 0)
                string byteString = Encoding.UTF8.GetString(data);
                Device device = (Device)JsonConverter.DeserializeObject(byteString, typeof(Device));
                return device;
            return null;

I got something to work with a much simpler approach using Reflection.

To convert the configuration to the data stream I used this with data being a byte array.

data = Reflection.Serialize(configData, typeof(ConfigData));

To convert the byte stream back to the config data, I use this

configData = (ConfigData)Reflection.Deserialize(data, typeof(ConfigData));

The above works a charm. Thanks for the heads up.

1 Like

Dave is right - json is for interop and/or for preserving the data where a schema that might change over time. Serialization is better for save/restore on the same machine and with an unchanging schema.