5

I am using the following code:

myObj jsonStream = ser.Deserialize<myObj>(jsonStream);

And all was working fine until the JSON that came back had a null value for one of the fields. i.e.:

"name" : null

During the deserialization process, it's throwing an exception. In my myObj, I have a member:

public string name;

How can I gracefully handle the odd null value coming back from my datasource using the System.Web.Script.Serialization assembly? I tried:

public string name = "";

But that didn't work.

1
  • 2
    I can't gather from your question what the type of "ser" is. Commented Nov 13, 2009 at 9:07

3 Answers 3

5

Try to use nullable type

public string? name;
Sign up to request clarification or add additional context in comments.

2 Comments

oh, I didn't know. But I'd try :)
This is actually the right answer in that I had to allowable nullable. It turns out the example I used was a string, but it was the int that needed to be int?. I just used a string for my example. So, don't do "string?" for the reasons that Jauco points out, but this is the answer to my issue.
2

You can supply settings to JsonConvert.DeserializeObject to tell it how to handle null values, in this case, and much more:

var settings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    };
var jsonModel = JsonConvert.DeserializeObject<Customer>(jsonString, settings);

1 Comment

Still be useful in 2022.
1

Maybe the problem lies somewhere else because the following code worked fine for me using JavaScriptSerializer (it correctly handled the null without throwing any exception):

public class MyObj
{
    public string name;
}

class Program
{
    static void Main(string[] args)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        var json = "{\"name\" : null}";
        var myObj = ser.Deserialize<MyObj>(json);
        Console.WriteLine(myObj.name);
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.