I am using Entity Framework as my ORM. It has ComplexTypeAttribute
(which is used to annotate POCO's). Properties that are complex types, are always instantiated (using default constructor), regardless of their value; And as a consequence, are always serialized by ServiceStack JsonSerializer
(along with their properties).
JSON.NET has an enum called DefaultValueHandling
, which can be used in these situations.
Does ServiceStack have something similar?
For example:
class Person
{
string Name { get; set; }
Address Address { get; set; }
}
[ComplexType]
class Address
{
string Street { get; set; }
int Number { get; set; }
int PostalCode { get; set; }
}
When I serialize a person that doesn't have address I get this:
"{ Name: Jim, Address : { Number: 0, PostalCode: 0 } }"
In Json.Net if I set DefaultValueHandling to Ignore, I only get
"{ Name: Jim }"
Yes, here are the different ways you can ignore properties with ServiceStack's JSON and Text serializers.
The serializers also support multiple hooks to customize serialization and deserialization.
The JsConfig class shows all the customizations that are possible.
Please consider changing your value types to nullable data types and set null as default value for any reference type.
This should help you get rid of attributes with default values as ServiceStack Text will omit properties with null value. Also observe that 'Age' which is of type int? is omitted from serialized output when it is null. The example also demonstrates serialization using anonymous objects.
Example below:
Output: