Newtonsoft.Json 某属性不序列化咋办呢

xloveme 2015-07-31 03:41:20

使用 Newtonsoft.Json 得到 JSON 还是挺方便的, JsonConvert.SerializeObject(this); 就解决了。
但是,如果一个属性,不需要序列化,该怎么把它排除呢?

比方一个respose类,里面有个header类型,还有个body类
public class respose{

  public header header{get;set}
  public body body{get;set}

}

比如我不想要序列化出这个body,该怎么做

最终显示的应该是{respose:{header:XXX}}
而不是{respose:{header:XXX,body:XXX}}
...全文
5131 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
showjim 2015-07-31
  • 打赏
  • 举报
回复
试试fastCSharp,你可以这样
 using fastCSharp;
       public class respose
        {
            public string header { get; set; }
            [fastCSharp.emit.jsonSerialize.member(IsIgnoreCurrent = true)]
            public string body { get; set; }
        }
            string json = new respose { header = "A", body = "B" }.ToJson();
也可以这样
using fastCSharp;
        public class respose
        {
            public string header { get; set; }
            public string body { get; set; }
        }
        private static readonly fastCSharp.emit.jsonSerializer.config jsonConfig = new fastCSharp.emit.jsonSerializer.config { MemberMap = fastCSharp.code.memberMap<respose>.CreateBuilder().Append(value => value.header) };
            string json = new respose { header = "A", body = "B" }.ToJson(jsonConfig);
宝_爸 2015-07-31
  • 打赏
  • 举报
回复 2
[JsonIgnore] attribute也可以。 public class Car { // included in JSON public string Model { get; set; } public DateTime Year { get; set; } public List<string> Features { get; set; } // ignored [JsonIgnore] public DateTime LastModified { get; set; } } 以上来自: http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size
ruanwei1987 2015-07-31
  • 打赏
  • 举报
回复
用匿名类 new{instance.header}
  • 打赏
  • 举报
回复
http://www.cnblogs.com/yanweidie/p/4605212.html 睡到一半热醒的悲剧,开空调睡又吃不消,尼玛
smthgdin_020 2015-07-31
  • 打赏
  • 举报
回复
加上 [JsonIgnore]就行了。

110,567

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧