8

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

super cool
  • 6,003
  • 2
  • 30
  • 63
  • Than surround the code with try/catch; catch the exact exception; and do whatever you want with the object. – bjaksic Jun 17 '15 at 12:38
  • You might need to look into [Custom Conversion](http://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base) or utilize dynamics by using `JsonConvert.DeserializeObject(jsonData);` and then doing another process to convert that dynamic into a fully qualified object (NewtonTest, in your case). – JasonWilczak Jun 17 '15 at 12:40
  • dynamic wont work for me i tried as i have 4 inner loops so in real scenario :) . – super cool Jun 17 '15 at 12:43
  • 1
    Your class structure doesn't match your JSON. Why aren't you creating a valid JSON? – Yuval Itzchakov Jun 17 '15 at 12:44
  • How would a value of `1339886` be able to be converted to a complex object that is typeof `Element` –  Jun 17 '15 at 12:49
  • 1
    If your json data matches it will work correctly. var jsonData = "{\"test\": {\"sample\": \"1339886\"}}"; – Louis Lewis Jun 17 '15 at 12:52
  • 1
    yes if json data matches perfectly everything will work . but there is a chance data coming in like that i should be handling it that's the case here . may be 1 out of 100 time . i should not leave it to chance , json data coming via user upload – super cool Jun 17 '15 at 15:40

2 Answers2

8

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.

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307
0

If you want a work around while using the badly formed json data. 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);
Louis Lewis
  • 1,298
  • 10
  • 25
  • appreciate your try . my case is a very rare case but i should be in a position to handle it rather modifying model(class ) – super cool Jun 17 '15 at 15:45