有没有办法在ServiceStack json序列化期间忽略默认值?

时间:2013-02-14 18:08:15

标签: json servicestack

我使用Entity Framework作为我的ORM。它有ComplexTypeAttribute(用于注释POCO)。复杂类型的属性总是被实例化(使用默认构造函数),而不管它们的值如何;因此,始终由ServiceStack JsonSerializer(以及它们的属性)序列化。

JSON.NET有一个名为DefaultValueHandling的枚举,可以在这些情况下使用。

ServiceStack有类似的东西吗?

例如:

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; }
}

当我序列化一个没有地址的人时,我得到了这个:

"{ Name: Jim, Address : { Number: 0, PostalCode: 0 } }" 

在Json.Net中,如果我将DefaultValueHandling设置为Ignore,我只会得到

 "{ Name: Jim }"

2 个答案:

答案 0 :(得分:4)

是的,以下是ignore properties with ServiceStack's JSON and Text serializers的不同方法。

序列化程序也support multiple hooks to customize serialization and deserialization

JsConfig类显示可能的所有自定义。

答案 1 :(得分:1)

请考虑将您的值类型更改为可为空的数据类型,并将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值的属性。还要注意'Age'是int类型吗?如果为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":[]}]}