我现在用Newtonsoft将对象转成json字符串,如果对象中有字节数组,转出来的结果就是个basic64字符串,比如byte[] arr = new byte[10],转出来就是AAAAAAAAAAAAAA==,有没有什么办法能禁止这种格式,将其改成和其他数组一样的[0,0,0,0,0,0,0,0,0,0]这类的形式
可以自己写一个自定义序列化, 大概就是这样子
new JsonSerializerSettings().Converters.add(new myByteConverter())
class myByteConverter: Newtonsoft.Json.Converters.CustomCreationConverter<byte[]>{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteStartArray();
(value as byte[]).Each(b=>writer.WriteValue(b))
writer.WriteEndArray();
}
}
我照着试了下,还是不行啊,断点调试,感觉根本就没有走myByteConverter的WriteJson,
@WmW: 上代码
@czd890:
class JsonTest {
class MyBinaryConverter : BinaryConverter {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
writer.WriteStartArray();
foreach (var b in (value as byte[])) {
writer.WriteValue(b);
}
writer.WriteEndArray();
}
}
public JsonTest() {
new JsonSerializerSettings().Converters.Add(new MyBinaryConverter());
}
public string GetJson<T>(T obj) {
return JsonConvert.SerializeObject(obj);
}
class Model {
public string Name { get; set; }
public byte[] Data { get; set; }
public int[] Buffer { get; set; }
}
public void Test() {
Model aaa = new Model();
aaa.Name = "张三";
aaa.Data = new byte[10];
aaa.Buffer = new int[10];
Console.WriteLine(GetJson(aaa));
}
}
@czd890: 控制台程序中
JsonTest jsonTest = new JsonTest();
jsonTest.Test();
@WmW:
JsonConvert.SerializeObject(obj, 请传入你自定义的JsonSerializerSettings);
另外MyBinaryConverter : BinaryConverter , 我可不是继承BinaryConverter 哦
@czd890: 还是不行啊,
class JsonTest {
class MyConverter : CustomCreationConverter<byte[]> {
public override byte[] Create(Type objectType) {
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
writer.WriteStartArray();
foreach (var b in (value as byte[])) {
writer.WriteValue(b);
}
writer.WriteEndArray();
}
}
JsonSerializerSettings settings = new JsonSerializerSettings();
public JsonTest() {
settings.Converters.Add(new MyConverter());
}
public string GetJson<T>(T obj) {
return JsonConvert.SerializeObject(obj, settings);
}
class Model {
public string Name { get; set; }
public byte[] Data { get; set; }
public int[] Buffer { get; set; }
}
public void Test() {
Model aaa = new Model();
aaa.Name = "张三";
aaa.Data = new byte[10];
aaa.Buffer = new int[10];
Console.WriteLine(GetJson(aaa));
}
}
@WmW:
MyConverter override CanWrite 返回true.
@czd890: 可以了,感谢