gpt4 book ai didi

c# - Newton Soft Json JsonSerializerSettings for object with Property as byte array

转载 作者:行者123 更新时间:2023-11-30 14:35:36 25 4
gpt4 key购买 nike

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

例如

class A
{
public int X {get;set;}
public byte[] Y {get;set;}
}

当我将 A 序列化为 json 时,我没有像我设置的那样获得 Y 的值... byte[] 的输出应该是十六进制

最佳答案

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("-", ""));
}
}

关于c# - Newton Soft Json JsonSerializerSettings for object with Property as byte array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11829035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com