问题
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