Configure ServiceStack.Text to throw on invalid JS

2019-02-24 07:08发布

Is it possible to make the ServiceStack.Text library throw when attempting to deserialize invalid JSON. By default it looks as if invalid JSON is just ignored, so that the result object contains null values.

When I attempt to deserialize this json (a " is missing after MongoConnectionString)

{
"MongoDb": {
"MongoConnectionString:"mongodb://localhost:27017/x",
"MongoDatabase":"x",    
"MongoSafeModeEnabled":true, 
"MongoSafeModeFSync":true,
"MongoSafeModeWriteReplicationCount":
"MongoSafeModeWriteTimeout":"00:00:00"
},

by doing this: JsonSerializer.DeserializeFromString(json); where

public class Configuration {
    public class MongoDbSettings
    {
        public string MongoConnectionString {get;set;}
        public string MongoDatabase {get;set;}
        public bool MongoSafeModeEnabled {get;set;}
        public bool MongoSafeModeFSync {get;set;}
        public int MongoSafeModeWriteReplicationCount {get;set;}
        public TimeSpan MongoSafeModeWriteTimeout {get;set;}
    }
}

I get a Configuration object where MongoDbSettings is null. I would prefer to get an exeception in this case. Is this possible?

1条回答
何必那么认真
2楼-- · 2019-02-24 07:36

At the moment the ServiceStack serializers are optimized for resilience, i.e. deserialize as much as possible without error.

I'd recommend adding some of your own validation checking post serialization to work out which fields weren't deserialized correctly.

You could also submit a pull-request to the ServiceStack.Text project that supports an opt-in flag (i.e. on JsConfig) to change the behavior to throw exceptions.

查看更多
登录 后发表回答