我可以将ServiceStack反序列化为1的json值为true吗?

时间:2012-06-14 00:30:13

标签: deserialization servicestack

我可以将ServiceStack反序列化为1的json值为真吗? 这是一个单元测试,显示了我想要做的事情。 这可能吗?如果是这样的话?

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);
}

2 个答案:

答案 0 :(得分:1)

现在可以从v3.9.55 +。

获得built into ServiceStack.Text with this commit

答案 1 :(得分:0)

编辑这是我的解决方案,但请查看Mythz,因为我相信它也会有效。

我反序列化为自定义结构MyBool而不是bool 这是MyBool结构的代码。

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;
    }

并将Foo更改为:

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

批评欢迎。