tags:

views:

82

answers:

2

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.

A: 

Try to use nullable type

public string? name;
valya
string is always nullable
Jauco
oh, I didn't know. But I'd try :)
valya
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.
Brandon Watson
+1  A: 

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);
    }
}
Darin Dimitrov