简体   繁体   中英

How to serialize Nullable<bool>?

I want to serialize a nullable bool simply by converting it to a string

public static string SerializeNullableBoolean(bool? b)
{
    if (b == null)
    {
        return "null or -1 or .."; // What to return here?
    }
    else
    {
        return b.ToString();
    }
}

What is the most appropriate string to serialize the null-value as?

Since bool.ToString() returns "True" or "False", I would go with "Null". I would also rewrite this as:

return b.HasValue ? b.ToString() : "Null";

Edit: I take that back. bool?.ToString() returns empty string, so I would decide based on what's more convenient. If a person needs to read the output then "Null" is a better choice; if it only needs to be used in code then empty string is fine. If you go with empty string it is as simple as:

return b.ToString();

Why not:

b.ToString()

If b is null, then it returns an empty string. Since that's what the framework returns, I would use it to be consistent. This is also what XmlSerializer uses for nullable scalars.

我会选择一个空字符串来表示空值。

如果你为真正的bool值返回True / False,那么在bnull情况下你应该返回Null以保持对称性。

Be consistent.

b.ToString()

returns the strings 'true' or 'false'. Thus if you return -1 it will be less consistent if you actually read the serialized files. The deserialization code will also become more "ugly" and less readable.

I would choose to serialize it to either the string 'unset' (or something along those lines) or the string 'null'. Unless you have really strict space requirements or really huge datasets to serialize the extra characters shouldn't really matter.

If you are using the built in XmlSerializer you can also do the following to serialize the value (and prevent a lot of ugly custom serialization code):

    [Serializable]
    public class Foo
    {
        [XmlIgnore]
        public bool? Bar { get; set; }

        [XmlAttribute("Bar")]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public string xmlBar
        {
            get { return Bar.ToString(); }
            set
            {
                if (string.IsNullOrEmpty(value)) Bar = null;
                else Bar = bool.Parse(value);
            }
        }
    }

Personally I wouldn't use any of the above but simply use ShouldSerialize interface. For example,

[XmlElement("SomeBoolean ", Namespace = "SomeNamespace")]
public bool? SomeBoolean { get; set; }
public bool ShouldSerializeSomeBoolean() { return SomeBoolean.HasValue; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM