0

We're using JSON.NET to convert a tiered object into JSON, then from there into XML.

We're aware of the arguments against doing this, but there are several arguments in favor of it, and we've tried a lot of things to get here.

An issue we're running into is that occasionally a property will have a null value. When the property is getting converted to an element, that's fine, but when it's an attribute, we get a NullReferenceException thrown. Our preference would be to have nulls get converted to empty strings, however leaving them out entirely would be acceptable.

How can we handle this?

Community
  • 1
  • 1
J.D. Ray
  • 697
  • 1
  • 8
  • 22

1 Answers1

0

A little bit of analysis turned up that all the NullReferenceExceptions we were getting were on string properties. I put the following in the getter to return string.Empty instead of null if indeed the string hadn't been initialized. This is not an elegant solution, however it works for our situation.

    [JsonProperty(PropertyName = "@Code")]
    public string ProductCode
    {
        get { return _productCode == null ? string.Empty : _productCode ; }
        set { _productCode = value.Trim(); }
    }
J.D. Ray
  • 697
  • 1
  • 8
  • 22