Deserialize Json in C # - How to handle null Return Values

I am using the following code:

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

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

"name" : null

During the deserialization process, he throws an exception. In my myObj, I have a member:

public string name;

How can I gracefully handle the odd null returned from my data source using the System.Web.Script.Serialization assembly? I tried:

public string name = "";

But that did not work.

+3
source share
2 answers

Try using a type with a null value

public string? name;
+1
source

, - , , JavaScriptSerializer ( , ):

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);
    }
}
+1

Source: https://habr.com/ru/post/1722764/


All Articles