如何排除JSON序列化属性 [英] How to exclude property from Json Serialization

查看:108
本文介绍了如何排除JSON序列化属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我序列化的DTO类

  Json.Serialize(MyClass的)

我怎样才能排除公开它的财产?

(它必须是公开的,正如我在code别的地方使用它)


解决方案

您可以把<一个href=\"http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx\"><$c$c>ScriptIgnore属性上不应序列的成员。请参阅从<一个采取的例子href=\"http://www.creave.dk/post/2009/10/07/Excluding-properties-from-being-serialized-in-ASPNET-MVC-JsonResult.aspx\">here:


  

考虑以下(简化)情况:

 公共类用户{
    公众诠释标识{搞定;组; }
    公共字符串名称{;组; }
    [ScriptIgnore]
    公共BOOL IsComplete
    {
        {返回标识&GT; 0安培;&安培; !string.IsNullOrEmpty(姓名); }
    }
}

在这种情况下,只有Id和Name属性将被序列化,产生的JSON对象是这样的:

  {ID:3,名称:'测试用户'}


PS。不要忘了添加引用 System.Web.Extensions程序这个工作

I have a DTO class which I Serialize

Json.Serialize(MyClass)

How can I exclude a public property of it?

(It has to be public, as I use it in my code somewhere else)

解决方案

You can put a ScriptIgnore attribute on the members that shouldn't be serialized. See the example taken from here:

Consider the following (simplified) case:

public class User {
    public int Id { get; set; }
    public string Name { get; set; }
    [ScriptIgnore]
    public bool IsComplete
    {
        get { return Id > 0 && !string.IsNullOrEmpty(Name); }
    } 
} 

In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:

{ Id: 3, Name: 'Test User' }

PS. Don't forget to add a reference to "System.Web.Extensions" for this to work

这篇关于如何排除JSON序列化属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆