将字节数组序列化为字符串
本文关键字:字符串 序列化 数组 字节 字节数 | 更新日期: 2023-09-27 18:16:38
我有一个IP地址,我需要有一个4字节数组在我的代码。然而,我想把它存储在我的JSON设置文件作为一个字符串,格式化为"192.168.0.1"。然后我也想做相反的,反序列化它。
我想这样做作为我的设置的目标。Json文件是可编辑的。
我可以这样做吗?
我使用Newtonsoft JSON包
类我正在序列化
public class Settings
{
public string PLCIP;
public byte[] RightTesterIP;
public byte[] LeftTesterIP;
}
我编写的转换器方法。只是不确定在哪里实现它们。
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;
}
您可以在自定义的JsonConverter
中这样做:
public class IPByteArrayConverter : JsonConverter
{
private static 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 static byte[] ConvertIPStringToByteArray(string ip)
{
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;
}
public override bool CanConvert(Type objectType)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
if (token.Type == JTokenType.Bytes)
return (byte[])token;
return ConvertIPStringToByteArray((string)token);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var bytes = (byte[])value;
writer.WriteValue(ConvertIPByteArraytoString(bytes));
}
}
然后使用[JsonConverter(IPByteArrayConverter)]
将其附加到适当的属性或字段:
public class Settings
{
public string PLCIP;
[JsonConverter(typeof(IPByteArrayConverter))]
public byte[] RightTesterIP;
[JsonConverter(typeof(IPByteArrayConverter))]
public byte[] LeftTesterIP;
}
样本小提琴。
使用IPAddress
作为建议的@Greg让你支持IPV6以及IPV4。此类型的JsonConverter
如下所示:
public class IPAddressConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(IPAddress).IsAssignableFrom(objectType);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var token = JToken.Load(reader);
if (token.Type == JTokenType.Bytes)
{
var bytes = (byte[])token;
return new IPAddress(bytes);
}
else
{
var s = (string)token;
return IPAddress.Parse(s);
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var ip = (IPAddress)value;
writer.WriteValue(ip.ToString());
}
}
然后像以前一样将其应用于Settings
类,或者在JsonSerializerSettings.Converters
中全局使用它:
var jsonSettings = new JsonSerializerSettings
{
Converters = new [] { new IPAddressConverter() },
};
var json = JsonConvert.SerializeObject(settings, jsonSettings);
使用类:
public class Settings
{
public string PLCIP;
public IPAddress RightTesterIP;
public IPAddress LeftTesterIP;
}
样本小提琴。