请考虑将您的值类型更改为可为空的数据类型,并将 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 将省略具有空值的属性。还要观察int类型的'Age'?当它为空时,从序列化输出中省略。该示例还演示了使用匿名对象的序列化。
下面的例子:
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":[]}]}