4

我使用实体框架作为我的 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 }"
4

2 回答 2

4

是的,您可以通过以下不同方式忽略 ServiceStack 的 JSON 和 Text 序列化程序的属性

序列化程序还支持多个挂钩来自定义序列化和反序列化

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

于 2013-02-14T20:26:29.280 回答
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 将省略具有空值的属性。还要观察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":[]}]}
于 2015-03-03T11:44:06.273 回答