比方一个respose类,里面有个header类型,还有个body类
public class respose{
public header header{get;set}
public body body{get;set}
}
比如我不想要序列化出这个body,该怎么做
最终显示的应该是{respose:{header:null}}
而不是{respose:{header:null,body:null}}
public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { var response = new response { header = new header { rspCode = "0000", rspDesc = "执行成功", rspErrorMsg = "", rspTime = DateTime.Now }, body = new body { order = new order { orderid = "S0000001" } } }; var json = JsonConvert.SerializeObject(response); label1.Text = json; } } public class response { public header header { get; set; } public body body { get; set; } } public class header { public string rspCode { get; set; } public string rspDesc { get; set; } public string rspErrorMsg { get; set; } public DateTime rspTime { get; set; } } public class body { public order order { get; set; } public product product { get; set; } } public class order { public string orderid { get; set; } } public class product { public string productid { get; set; } }
这种显示出来的是:
{"header":{"rspCode":"0000","rspDesc":"执行成功","rspErrorMsg":"","rspTime":"2014-03-05T13:40:48.7162196+08:00"},"body":{"order":{"orderid":"S0000001"},"product":null}}
但是我其实想的是,如果我product没有在button1_Click里面写的话,那我就不要把这个给序列化出来的
看你用的是什么Json解析库,一般都会提供[Ignore]特性,来忽略指定属性。
看下我补充的
@Nemo_Li:得看你的SerializationHelper的具体实现了。
@幻天芒:我换了个第三方的DLL,Newtonsoft.Json
@幻天芒: 算了,看起来好像我那个也不需要,我这是给一个客户端写接口的,客户端接收的话就直接反序列号为一个实体了,如果product为null就不用它就行了
@幻天芒: 不过还有个问题想问一下,Newtonsoft.Json这个DLL能不能显式的将我要的实体序列化出来,就是里面如果有值是null就不变成JSON
{"header":{"rspCode":"0000","rspDesc":"执行成功","rspErrorMsg":"","rspTime":"2014-03-05T13:40:48.7162196+08:00"},"body":{"order":{"orderid":"S0000001"},"product":null}}
改变后
{"header":{"rspCode":"0000","rspDesc":"执行成功","rspErrorMsg":"","rspTime":"2014-03-05T13:40:48.7162196+08:00"},"body":{"order":{"orderid":"S0000001"}}}
@幻天芒: 搞定
var jSetting = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}; var json = JsonConvert.SerializeObject(response, Formatting.Indented, jSetting);
@Nemo_Li: 挺好的实现方式~