値の型を null 許容データ型に変更し、参照型の既定値として null を設定することを検討してください。
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; }
}
これは、ServiceStack Text が null 値を持つプロパティを省略するため、デフォルト値を持つ属性を取り除くのに役立ちます。int型の「Age」にも注意してください。null の場合、シリアル化された出力から省略されます。この例では、匿名オブジェクトを使用したシリアル化も示しています。
以下の例:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack;
namespace JsonTest
{
class Person
{
public string Name { get; set; }
public string Address { get; set; }
public int? Age { get; set; }
public List<Person> Children { get; set; }
public Person()
{
Children = new List<Person>();
}
}
class Program
{
static void Main(string[] args)
{
var c1 = new Person { Name = "John", Address = "USA", Age = null };
var c2 = new Person { Name = "John", Address = "USA", Age = 12 };
List<Person> children = new List<Person>();
children.Add(c1);
string name = "Jim";
// Uncomment lines below and check - Children attribute is omitted from JSON result
// children = null;
// name = null;
var p1 = new { Name = name, Address = "USA", Age=40, Children = children};
var p2 = new Person { Name = "Jim", Address = "USA" , Age = null};
p2.Children.Add(c2);
Console.WriteLine(p1.ToJson());
Console.WriteLine(p2.ToJson());
Console.ReadLine();
}
}
}
出力:
{"Name":"Jim","Address":"USA","Age":40,"Children":[{"Name":"John","Address":"USA","Children":[]}]}
{"Name":"Jim","Address":"USA","Children":[{"Name":"John","Address":"USA","Age":12,"Children":[]}]}
{"Address":"USA","Age":40}
{"Name":"Jim","Address":"USA","Children":[{"Name":"John","Address":"USA","Age":12,"Children":[]}]}