快速提问:
在JSONNet中-如何获取布尔true / false以序列化为布尔1/0
我可以看到我们如何处理空值,而所有这些似乎都找不到如何执行此操作。
这可能吗?
您可以像这样实现自定义转换器:
[TestFixture] public class CustomJsonSerialization { [Test] public void Test() { string serializeObject = JsonConvert.SerializeObject(true, new BoolConverter()); Assert.That(serializeObject, Is.EqualTo("1")); var deserializeObject = JsonConvert.DeserializeObject<bool>(serializeObject, new BoolConverter()); Assert.That(deserializeObject, Is.True); } } public class BoolConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((bool)value) ? 1 : 0); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value.ToString() == "1"; } public override bool CanConvert(Type objectType) { return objectType == typeof(bool); } }