Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to bool during JSON deserialization

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.

like image 362
tobi.at Avatar asked Jun 25 '13 18:06

tobi.at


1 Answers

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.

like image 95
mythz Avatar answered Sep 27 '22 16:09

mythz