Share via


How can i desrialize an empty string to object fields ?

Question

Tuesday, March 31, 2020 7:09 AM

I have the following

public class UserDetails
{
public string FirstName{ get; set; }
public string LastName { get; set; }
public string Address { get; set; }

public bool HasId { get; set; }
}

var JsonStr = "";

if I deserialize into UserDetails I get null as follows:         

var deserializedStr = JsonConvert.DeserializeObject<UserDetails>(JsonStr);

can I deserialize in such a way that default values are oput in for the DataType ?

So I get something like 

{

FristName: ""

LastName: ""

Address : ""

HasId: false

}

All replies (2)

Tuesday, March 31, 2020 8:23 AM âś…Answered

Hi,

Which deserializer are you using? See for example https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_DefaultValueHandling.htm that explains how default values are handled though my personal preference would be likely to serialize exactly what I want on the other side if I can (seems a bit weird to deserialiaze something which is entirely empty)...


Tuesday, March 31, 2020 9:19 AM

Hi robby32,

 

It is possible to assign the default values as an output of "null" for a certain data type.

Solution:

Using DefaultValueHandling = DefaultValueHandling.Populate AND attribute [DefaultValue()].

Code:

static void Main(string[] args)
        {
            var JsonStr = "{}";
            var settings = new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Populate};

            UserDetails deserializedStr = JsonConvert.DeserializeObject<UserDetails>(JsonStr, settings);
        

            Console.WriteLine("FirstName:{0}, LastName:{1}, Address:{2}, HasId:{3} ",deserializedStr.FirstName,deserializedStr.LastName,deserializedStr.Address,deserializedStr.HasId);
            Console.ReadLine();
        }

        public class UserDetails
        {
            [DefaultValue("FirstName1")]
            public string FirstName { get; set; }

            [DefaultValue("LastName1")]
            public string LastName { get; set; }

            [DefaultValue("Address1")]
            public string Address { get; set; }

            [DefaultValue(true)]
            public bool HasId { get; set; } = true;
        }

Output:

  

Hope this can help you.

Best regards,

Sean