Configure ServiceStack.Text to throw on invalid JSON

独自空忆成欢 提交于 2019-12-01 19:27:54

问题


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:


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.



来源:https://stackoverflow.com/questions/8972556/configure-servicestack-text-to-throw-on-invalid-json

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