Convert int to bool during JSON deserialization

I get a JSON object using RestSharp. Therefore, I wrote my own deserializer that implements ServiceStack.Text:

public T Deserialize<T>(IRestResponse response) { return JsonSerializer.DeserializeFromString<T>(response.Content); } 

The response maps to POCO, which uses System.Runtime.Serialization to provide a better match. This works fine, but not for logical ones. Many properties are returned that are 1 or 0 (ints).

For example: { favorite: 1 }

The problem here is that I don’t know how to convert this to Boolean in my POCO.
This will not work (for sure):

 [DataContract] public class Item { [DataMember(Name = "favorite")] public bool IsFavorite { get; set; } } 

Any suggestions on how to make it work?

I not only want to know this for int <=> bool, but for all types of transforms in general.

+4
source share
1 answer

Edit:

I just supported the built-in support , so in the next version of ServiceStack.Text (v3.9.55 +) you can deserialize 0 , 1 , true , false to boolean, for example:

 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:

 JsConfig<bool>.DeSerializeFn = x => x.Length == 1 ? x == "1" : bool.Parse(x); 

All ServiceStack.Text settings are available on JsConfig .

Other available hooks include JsConfig<T>.RawSerializeFn and JsConfig<T>.RawDeserializeFn , which allow you to override custom serialization of custom POCO.

If you just want some kind of preprocessing / post processing to also execute the custom interceptors JsConfig<T>.OnSerializingFn and JsConfig<T>.OnDeserializedFn .

Here's an earlier example of using custom deserialization using a custom MyBool structure .

See ServiceStack.Text tests for examples of the above custom interceptors.

+4
source

Source: https://habr.com/ru/post/1488145/


All Articles