How to ignore type when deserializing with Newtonsoft.Json

I am trying to deserialize the json data I have relative to the model class i,

Json:

"{'test':'1339886'}"

      

Classes:

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

      

In the main class:

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

      

Error information: // innner exception

Unable to convert or convert from System.String to Test.Element. "

I completely understand what the error says when I miss string

in mine json

where, as in class i, there is type class

as type (mismatch).

In such cases, I need to handle the error and maybe put a null if there is a mismatch in the output, but it shouldn't throw an exception.

I tried my best to read the docs and settings using settings but none seem to work.

I am using version 4.5 of Newtonsoft.Json

+3


source to share


2 answers


You can tell JSON.NET to ignore errors for certain 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 will not throw an exception. The handler Error

in the settings object will be called, and if the member throwing the exception is named "test"

and owned NewtonTest

, the error will be ignored and JSON.NET will continue to run.

The property ErrorContext

also has other properties that you can use to handle errors that you are absolutely sure you want to ignore.

+3


source


If you want to work using poorly formed json data. Here's 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;
    }
}

      



What can be used like

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

      

0


source







All Articles