在反序列化为C#对象之前验证JSON [英] Validating JSON before deserializing into C# object

查看:171
本文介绍了在反序列化为C#对象之前验证JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果JSON中的JavaScript对象不会反序列化为我想要的C#对象,我该如何查询它以提供一条错误消息,说明输入内容有问题? (假设JSON格式正确,只是数据无效.)

If a JavaScript object in JSON is not going to deserialize into the C# object I want, how can I interrogate it to provide an error message explaining what is wrong with the input? (Assuming the JSON format is correct, just the data is not valid.)

我的C#类:(简体)

public class Dependent
{
    public Dependent()
    {
    }
    public string FirstName { get; set; }
    public DateTime DateOfBirth { get; set; }
}

要反序列化的测试代码:

string dependents = @"[
                            {
                                ""FirstName"": ""Kenneth"",
                                ""DateOfBirth"": ""02-08-2013""
                            },
                            {
                                ""FirstName"": ""Ronald"",
                                ""DateOfBirth"": ""08-07-2011""
                            }
                      ]";

JavaScriptSerializer jss = new JavaScriptSerializer();

List<Dependent> deps = new List<Dependent>();
deps = jss.Deserialize<List<Dependent>>(dependents);

这一切有效.除了将非日期作为生日传入之外,它将无法反序列化.

This all works. EXCEPT if a non-date is passed in as the birthday, it will fail to deserialize.

我想提供一个错误消息,例如相关2出生日期不是有效日期".或家属2必须小于18岁."

I want to provide an error message like "Dependent 2 date of birth is not a valid date." or "Dependent 2 must be under age 18."

如果JSON不反序列化到我的对象中,该如何验证JSON的详细信息?

可能的解决方案:

public class SerializableDependent
{
    public SerializableDependent()
    {
    }
    public string FirstName { get; set; }
    public string DateOfBirth { get; set; }
}

然后,将所有内容都作为字符串,我应该不会出现任何错误,并且可以遍历对象并进行验证.不过,这似乎是错误的.

And then I should not get any errors having everything as a string, and I can loop through the objects and do my validation. This seems wrong though.

推荐答案

JavaScriptSerializer不支持广泛的错误处理.我建议您使用 Json.NET库.您可以使用JsonSerializerSettings对象的Error事件处理程序来捕获有关发生问题的详细信息. 文档中提供了有关使用此成员的信息.

JavaScriptSerializer does not support extensive error handling. I suggest you use the Json.NET library. You can use the JsonSerializerSettings object's Error event handler to capture more details on what went wrong. Information on using this member is present in the documentation.

对于您上面的代码段,可以编写填充错误消息数组的处理程序,如下所示:

For your above code snippet, a handler which populates an array of error messages can be written as follows:

public class Dependent
{
    public Dependent()
    {
    }
    public string FirstName { get; set; }
    public DateTime? DateOfBirth { get; set; } // Use a nullable object to hold the error value
}

void DeserializeTest()
{
   string dependents = @"[
                            {
                                ""FirstName"": ""Kenneth"",
                                ""DateOfBirth"": ""02-08-2013""
                            },
                            {
                                ""FirstName"": ""Ronald"",
                                ""DateOfBirth"": ""asdf""
                            }
                      ]";

    var messages = new List<string>();

    var settings = new JsonSerializerSettings(){
        Error = (s,e)=>{
            var depObj = e.CurrentObject as Dependent;
            if(depObj != null)
            {
                messages.Add(string.Format("Obj:{0} Message:{1}",depObj.FirstName, e.ErrorContext.Error.Message));
            }
            else 
            {
                messages.Add(e.ErrorContext.Error.Message);
            }
            e.ErrorContext.Handled = true; // Set the datetime to a default value if not Nullable
        }
    };
    var ndeps = JsonConvert.DeserializeObject<Dependent[]>(dependents, settings);
    //ndeps contains the serialized objects, messages contains the errors
}

这篇关于在反序列化为C#对象之前验证JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆