[英]Serialize byte array property of class as boolean in json
I have the following class 我有以下课程
public class MyClass
{
public int Id { get; set; }
public byte[] Logo { get; set; }
}
I want to serialize Logo property in json as boolean: true if Logo is different than null, false otherwise. 我想将JSON中的Logo属性序列化为布尔值:如果Logo与null不同,则为true,否则为false。 How can I use JsonProperty decorator? 如何使用JsonProperty装饰器?
If you use the following JsonConverter
class, it will serialize how you want. 如果使用以下JsonConverter
类,它将序列化所需的方式。 I haven't implemented ReadJson
(deserialization), since the data is no longer there. 我没有实现ReadJson
(反序列化),因为数据不再存在。 There are other ways to implement this, I'm sure, but I simply serialized an anonymous object with the right data. 我敢肯定,还有其他方法可以实现此目的,但是我只是简单地序列化了带有正确数据的匿名对象。 At first, I tried to write a converter for byte[]
, but Json.NET apparently doesn't even try to use the converter for null
values, so it'd give null
or true
, instead of false
or true
. 最初,我尝试为byte[]
写一个转换器,但Json.NET显然甚至没有尝试将转换器用于null
值,因此它会给出null
或true
,而不是false
或true
。
public class MyClassConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return typeof(MyClass) == objectType;
}
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)
{
var myClass = (MyClass)value;
serializer.Serialize(writer, new { Id = myClass.Id,
Logo = myClass.Logo != null });
}
}
Either specify it as the converter for the class: 可以将其指定为该类的转换器:
[JsonConverter(typeof(MyClassConverter))]
public class MyClass
{
public int Id { get; set; }
public byte[] Logo { get; set; }
}
Or specify it when you're serializing (I'd recommend this if you can't modify MyClass
, or only sometimes want to serialize it like this): 或在序列化时指定它(如果您不能修改MyClass
,或者有时仅想像这样序列化,建议您这样做):
var s1 = JsonConvert.SerializeObject(new MyClass(), new MyClassConverter());
var s2 = JsonConvert.SerializeObject(new MyClass
{ Id = 1, Logo = new byte[] { 1, 2, 3, } }, new MyClassConverter());
Here's another way to do it. 这是另一种方法。 I'd prefer this if you're ok with adding a property and able to modify MyClass
: 如果您可以添加属性并能够修改MyClass
则我更愿意这样做:
public class MyClass
{
public int Id { get; set; }
[JsonProperty("Logo")]
public bool HasLogo { get { return Logo != null; } }
[JsonIgnore]
public byte[] Logo { get; set; }
}
Outputs something like: 输出类似:
{"Id":0,"Logo":false} // or
{"Id":1,"Logo":true}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.