我有以下代碼:JsonConverter字節[]
//模型
public class Home{
public Guid HomeId { get; set; }
public Guid UserId { get; set; }
public string Name { get; set; }
public byte[] Description1 { get; set; }
public virtual User User { get; set; }
}
public class User
{
public Guid UserId { get; set; }
public string Email { get; set; }
public virtual Perfil Perfil { get; set; }
}
public class Perfil
{
public Guid UserId { get; private set; }
public string Name { get; private set; }
public byte[] Description2 { get; set; }
}
// JsonConverter
public class ByteArrayConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(byte[]);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var m = Convert.FromBase64String((string)reader.Value);
return m;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
byte[] bytes = (byte[])value;
writer.WriteValue(Convert.ToBase64String(bytes));
}
}
//序列化(調用ByteArrayConverter的WriteJson功能,行)
var serialized = JsonConvert.SerializeObject(obj, settings);
{
"HomeId": "2925362b",
"UserId": "9ea43c30",
"Name": "Name 1",
"Description1": "VABlAHMAdABlAA==", //===> Converts to Base64 (OK)
"User": {
"UserId": "9ea43c30",
"Email": "[email protected]",
"Perfil": {
"UserId": "9ea43c30",
"Name": "Name 2",
"Description2": "dABlAHMAdABlAA==", //===> Converts to Base64 (OK)
}
}
}
//反序列
var deserialized = JsonConvert.DeserializeObject<T>(serialized, settings); // T is class Home
{
"HomeId": "2925362b",
"UserId": "9ea43c30",
"Name": "Name 1",
"Description1": "VABlAHMAdABlAA==", //===> Don't Convert from Base64, (**Does not call the ReadJson function of ByteArrayConverter**)
"User": {
"UserId": "9ea43c30",
"Email": "[email protected]",
"Perfil": {
"UserId": "9ea43c30",
"Name": "Name 2",
"Description2": "dABlAHMAdABlAA==", //===> Convert from Base64 (OK)
}
}
}
設置
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Objects,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented
};
settings.Converters.Add(new ByteArrayConverter());
的內容描述屬性不進入ByteArrayConverter類的ReadJson功能,因此它不會轉換回字節[],生成另一個無效的[]字節,....
任何標識這個問題的答案?
你不必ByteArrayConverter? Json.NET原生支持base64的字節數組,請參閱[序列化指南:原始類型](http://www.newtonsoft.com/json/help/html/serializationguide.htm) – dbc
嗨,當我不使用上述,它使用以下信息序列化byte []類型:$ type:「System.Byte [],mscorlib」 $ Value:「VABlAHMAdABlAA ==」,但是當我反序列化時,它顯示錯誤:解析值時遇到意外的字符 – Anpeiron
FWIW,沒有轉換器使用您指定的相同設置,它對我來說工作得很好。 –