首页 新闻 赞助 找找看

关于JSON序列化的问题,如果我不想将该实体中的某个属性序列化应该怎么做

0
悬赏园豆:10 [已解决问题] 解决于 2014-03-05 13:48

比方一个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里面写的话,那我就不要把这个给序列化出来的

Nemo_Li的主页 Nemo_Li | 初学一级 | 园豆:6
提问于:2014-03-05 09:37
< >
分享
最佳答案
0

看你用的是什么Json解析库,一般都会提供[Ignore]特性,来忽略指定属性。

收获园豆:10
幻天芒 | 高人七级 |园豆:37175 | 2014-03-05 12:38

看下我补充的

Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 13:30

@Nemo_Li:得看你的SerializationHelper的具体实现了。 

幻天芒 | 园豆:37175 (高人七级) | 2014-03-05 13:35

@幻天芒:我换了个第三方的DLL,Newtonsoft.Json

Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 13:41

@幻天芒: 算了,看起来好像我那个也不需要,我这是给一个客户端写接口的,客户端接收的话就直接反序列号为一个实体了,如果product为null就不用它就行了

Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 13:47

@幻天芒: 不过还有个问题想问一下,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"}}}
Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 14:57

@幻天芒: 搞定

var jSetting = new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore};
            var json = JsonConvert.SerializeObject(response, Formatting.Indented, jSetting);
Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 17:07

@Nemo_Li: 挺好的实现方式~

幻天芒 | 园豆:37175 (高人七级) | 2014-03-06 12:37
其他回答(1)
0

给个链接,感觉还不错。http://www.cnblogs.com/yank/p/3198082.html

单恋 | 园豆:678 (小虾三级) | 2014-03-05 10:13

看下我补充的

支持(0) 反对(0) Nemo_Li | 园豆:6 (初学一级) | 2014-03-05 13:30
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册