Can I make ServiceStack Deserialize json value of 1 as true?

馋奶兔 提交于 2020-01-05 04:33:12

问题


Can I make ServiceStack Deserialize json value of 1 as true?
Here's a unit test showing what I want to do. Is this possible? if so how?

public class Foo
{
    public bool isWorking { get; set; }
}

...

[Test]
public void Deserialise1AsBoolean()
{
    var json = @"{""isWorking"": 1}";
    var myFoo = json.FromJson<Foo>();
    Assert.IsTrue(myFoo.isWorking);
}

回答1:


This is now built into ServiceStack.Text with this commit available from v3.9.55+.




回答2:


EDIT Here's my solution, but please check out Mythz as well since I'm sure that will work also.

I deserialise to a custom struct MyBool rather than bool.
Here's the code for the MyBool struct.

public struct MyBool
{
    public bool Value { get; set; }

    public static MyBool Parse(string value)
    {
        return new MyBool {Value = (value == "1" || value=="true")};
    }

    public override string ToString()
    {
        return Value.ToString(CultureInfo.InvariantCulture);
    }

    public static implicit operator bool(MyBool lValue)
    {
        return lValue.Value;
    }

and change Foo to:

public class Foo
{
    public MyBool isWorking { get; set; }
}

Criticisms welcome.



来源:https://stackoverflow.com/questions/11025253/can-i-make-servicestack-deserialize-json-value-of-1-as-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!