30

我有一个对象,我正在使用ToJson<>()ServiceStack.Text 命名空间中的方法对其进行反序列化。

如何GET在序列化过程中省略所有唯一的属性?是否有任何属性[Ignore]可以用来装饰我的属性,以便可以省略它们?

谢谢

4

2 回答 2

57

ServiceStack 的 Text 序列化程序遵循 .NET 的 DataContract 序列化程序行为,这意味着您可以使用 opt-out[IgnoreDataMember]属性忽略数据成员

public class Poco 
{
    public int Id { get; set; }

    public string Name { get; set; }

    [IgnoreDataMember]
    public string IsIgnored { get; set; }
}

一个可选的替代方法是装饰你想要序列化的每个属性[DataMember]。其余属性未序列化,例如:

[DataContract]
public class Poco 
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Name { get; set; }

    public string IsIgnored { get; set; }
}

最后还有一个不需要属性的非侵入式选项,例如:

JsConfig<Poco>.ExcludePropertyNames = new [] { "IsIgnored" };

动态指定应该序列化的属性

ServiceStack 的序列化器还支持动态控制序列化,通过提供常规命名的ShouldSerialize({PropertyName})方法来指示属性是否应该序列化,例如:

public class Poco 
{
    public int Id { get; set; }

    public string Name { get; set; }

    public string IsIgnored { get; set; }

    public bool? ShouldSerialize(string fieldName)
    {
        return fieldName == "IsIgnored";
    }
}

ConditionalSerializationTests.cs中的更多示例

于 2013-02-13T18:00:38.993 回答
0

对于可为空的成员,您还可以在序列化之前将其设置为空。

如果您想创建一个可重复用于多个 API 调用的视图/api 模型,这将特别有用。服务可以在将其设置在响应对象上之前对其进行修改。

例子:

    public SignInPostResponse Post(SignInPost request)
    {
        UserAuthentication auth = _userService.SignIn(request.Domain, true, request.Username, request.Password);

        // Map domain model ojbect to API model object. These classes are used with several API calls.
        var webAuth = Map<WebUserAuthentication>(auth);

        // Exmaple: Clear a property that I don't want to return for this API call... for whatever reason.
        webAuth.AuthenticationType = null;

        var response = new SignInPostResponse { Results = webAuth };
        return response;
    }

我确实希望有一种方法可以以每个端点的方式动态控制所有成员(包括不可为空的)的序列化。

于 2016-02-11T19:25:18.063 回答