Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :

"{'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."

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) .

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

like image 505
super cool Avatar asked Jun 17 '15 12:06

super cool


1 Answers

You can tell JSON.NET to ignore errors for specific members and types:

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.

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.

like image 83
Andrew Whitaker Avatar answered Nov 14 '22 21:11

Andrew Whitaker