I have an IP address that I need to have as a 4 byte array in my code. However I would like to store it in my JSON settings file as a string, formatted like "192.168.0.1". Then I would also like to do the reverse and deserialize it.
I'd like to do this as the goal of my Settings.json file is that it is human editable.
Is there a way I can do this?
I'm using the Newtonsoft JSON package
Class I am serializing
public class Settings
{
public string PLCIP;
public byte[] RightTesterIP;
public byte[] LeftTesterIP;
}
converter methods I wrote. Just not sure where to implement them.
private string ConvertIPByteArraytoString(byte[] ip)
{
StringBuilder builder = new StringBuilder();
builder.Append(ip[0]);
for (int i = 1; i < ip.Length; i++)
{
builder.Append(".");
builder.Append(ip[i]);
}
return builder.ToString();
}
private byte[] ConvertIPStringToByteArray(string ip, string ParameterName)
{
var blah = new byte[4];
var split = ip.Split('.');
if (split.Length != 4)
{
//Log.Error("IP Address in settings does not have 4 octets.Number Parsed was {NumOfOCtets}", split.Length);
//throw new SettingsParameterException($"IP Address in settings does not have 4 octets. Number Parsed was {split.Length}");
}
for(int i = 0; i < split.Length; i++)
{
if(!byte.TryParse(split[i], out blah[i]))
{
//var ex = new SettingsParameterException($"Octet {i + 1} of {ParameterName} could not be parsed to byte. Contained \"{split[i]}\"");
//Log.Error(ex,"Octet {i + 1} of {ParameterName} could not be parsed to byte. Contained \"{split[i]}\"", i, ParameterName, split[i]);
//throw ex;
}
}
return blah;
}