简体   繁体   English

如何使用Newtonsoft.Json反序列化时忽略类型

[英]How to ignore type while Deserialization using Newtonsoft.Json

I am trying to Deserialize json data which i have to with respect to model class i have 我试图反序列化json数据,我必须与我的模型类

Json : 杰森:

"{'test':'1339886'}"

Classes : 课程:

public class NewtonTest
    {
        public Element test { get; set; }
    }
public class Element
    {
        public string sample { get; set; }
    }

In Main class : 在主类:

//under Main
string jsonData =  "{'test':'1339886'}";
var  = JsonConvert.DeserializeObject<NewtonTest>(jsonData);

Error Info : //innner exception 错误信息: //内在异常

Could not cast or convert from System.String to Test.Element." 无法从System.String转换或转换为Test.Element。“

I am completely aware of what the error states as i am passing string in my json where as in class i have a class as type(mismatch happening) . 我完全知道错误状态,因为我在我的json中传递string ,因为在类中我有一个class作为类型(不匹配发生)。

In such cases i need to handle the error and maybe place a null if there is mismatch in output but it should not throw exception . 在这种情况下,我需要处理错误,如果输出不匹配,可能会置空,但不应抛出异常。

I tried my best reading the docs and setting options via settings but none seem to work . 我尝试通过设置阅读文档和设置选项,但似乎没有任何工作。

I am using version 4.5 of Newtonsoft.Json 我使用的是Newtonsoft.Json 4.5版

You can tell JSON.NET to ignore errors for specific members and types: 可以告诉JSON.NET忽略特定成员和类型的错误:

var settings = new JsonSerializerSettings
{
    Error = (sender, args) => 
    {
        if (object.Equals(args.ErrorContext.Member, "test") && 
            args.ErrorContext.OriginalObject.GetType() == typeof(NewtonTest))
        {
            args.ErrorContext.Handled = true;
        }
    }
};

NewtonTest test = JsonConvert.DeserializeObject<NewtonTest>(json, settings);

This code won't throw an exception. 此代码不会抛出异常。 The Error handler in the settings object will get called and if the member throwing the exception is named "test" and belongs to NewtonTest , the error gets skipped over and JSON.NET keeps going. 将调用settings对象中的Error处理程序,如果抛出异常的成员名为"test"并且属于NewtonTestNewtonTest跳过错误并且JSON.NET继续运行。

The ErrorContext property also has other properties that you might want to leverage to only handle errors that you're absolutely sure you want to ignore. ErrorContext属性还有其他属性,您可能希望利用这些属性来仅处理您绝对确定要忽略的错误。

If you want a work around while using the badly formed json data. 如果你想在使用格式错误的json数据时进行解决。 Here is a simple solution that works. 这是一个有效的简单解决方案。

 public static class NewtonHelpers
{
    internal class NewtonHelper
    {
        public string test { get; set; }
    }

    public static NewtonTest BuildNewton(string jsonData)
    {
        var newtonHelper = JsonConvert.DeserializeObject<NewtonHelper>(jsonData);

        var newtonTest = new NewtonTest { test = { sample = newtonHelper.test } };

        return newtonTest;
    }
}

Which can be used like 哪个可以用

var testdata = "{'test':'1339886'}";
var newNewton = NewtonHelpers.BuildNewton(testdata);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM