本文介绍了配置ServiceStack.Text以抛出无效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试反序列化无效JSON时是否可以抛出ServiceStack.Text库.默认情况下,看起来好像只是忽略了无效的JSON,因此结果对象包含空值.

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.

当我尝试反序列化此json时(MongoConnectionString后缺少")

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"
},

通过执行以下操作

:JsonSerializer.DeserializeFromString(json);在哪里

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

我得到一个MongoDbSettings为null的Configuration对象.在这种情况下,我希望得到一个理解.这可能吗?

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

推荐答案

目前,ServiceStack序列化程序已针对弹性进行了优化,即尽可能多地反序列化而不会出错.

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.

您还可以向支持以下内容的 ServiceStack.Text 项目提交拉取请求.选择启用标志(即,在JsConfig上)以更改行为以引发异常.

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.

这篇关于配置ServiceStack.Text以抛出无效的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 12:39