Newton Soft Json JsonSerializerSettings 对象的属性为字节数组

use*_*223 5 c#

使用 Newton.Json 进行 Json 序列化。要应用什么 JsonSerializerSettings ,当我必须将具有属性的对象 Json 序列化为字节数组,然后以十六进制格式显示字节数组时..

例如

class A
{
  public int X {get;set;}
  public byte[] Y {get;set;}  
}
Run Code Online (Sandbox Code Playgroud)

当我将 A 序列化为 json 时,我没有得到 Y 的值,因为我已经设置了 ... byte[] 的输出应该是十六进制的

L.B*_*L.B 7

var json = JsonConvert.SerializeObject(new MyTestClass());

public class MyTestClass
{
    public string s = "iiiii";

    [JsonConverter(typeof(ByteArrayConvertor))]
    public byte[] buf = new byte[] {1,2,3,4,5};
}

public class ByteArrayConvertor : Newtonsoft.Json.JsonConverter
{

    public override bool CanConvert(Type objectType)
    {
        return objectType==typeof(byte[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        byte[] arr = (byte[])value;
        writer.WriteRaw(BitConverter.ToString(arr).Replace("-", ""));
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 我必须将“WriteRaw”更改为“WriteValue”才能使其正常工作。 (4认同)