I am receiving a JSON object with RestSharp. Therefor I've written a custom Deserializer, which implements ServiceStack.Text:
public T Deserialize<T>(IRestResponse response)
{
return JsonSerializer.DeserializeFromString<T>(response.Content);
}
The response is mapped to a POCO, which uses System.Runtime.Serialization
to provide better mapping.
That's working fine, but not for booleans.
There are a lot of properties returned, which are 1 or 0 (ints).
For example: { favorite: 1 }
The problem here is, I don't know how to convert this to a Boolean in my POCO.
This won't work (for sure):
[DataContract]
public class Item
{
[DataMember(Name = "favorite")]
public bool IsFavorite { get; set; }
}
Any suggestions on how to get it working?
I do not only want to know this for int <=> bool, but for all type conversions in general.
Edit:
I've just committed support built-in support for this, so in the next version of ServiceStack.Text (v3.9.55+) you can deserialize 0
, 1
, true
, false
into booleans, e.g:
var dto1 = "{\"favorite\":1}".FromJson<Item>();
Assert.That(dto1.IsFavorite, Is.True);
var dto0 = "{\"favorite\":0}".FromJson<Item>();
Assert.That(dto0.IsFavorite, Is.False);
var dtoTrue = "{\"favorite\":true}".FromJson<Item>();
Assert.That(dtoTrue.IsFavorite, Is.True);
var dtoFalse = "{\"favorite\":false}".FromJson<Item>();
Assert.That(dtoFalse.IsFavorite, Is.False);
You can do what you want with:
JsConfig<bool>.DeSerializeFn = x => x.Length == 1 ? x == "1" : bool.Parse(x);
All of ServiceStack.Text's customizations are available on JsConfig.
Other hooks available includes JsConfig<T>.RawSerializeFn
and JsConfig<T>.RawDeserializeFn
which lets you override the custom serialization of a custom POCO.
If you just want to some pre/post processing there's also the JsConfig<T>.OnSerializingFn
and JsConfig<T>.OnDeserializedFn
custom hooks.
Here's an earlier example of using a customizing deserialization using a custom MyBool struct.
See the ServiceStack.Text unit tests for examples of the above custom hooks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With