我有一个问题似乎很容易,但结果却是一个非常难的问题。
我写了这样的东西
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class UIService : System.Web.Services.WebService
{
public UIService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(EnableSession=true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[System.Security.Permissions.PrincipalPermission(System.Security.Permissions.SecurityAction.Demand, Authenticated = true)]
public Accordion ConstructAccordian(string accordionId)
{
Accordion result = new Accordion();
result.Name = "MenuAccordion";
AccordionItem item1 = new AccordionItem("Test");
item1.Items.Add(new MenuItem("User", "UserList"));
item1.Items.Add(new MenuItem("OnlineUser", "OnlineUser"));
result.Items.Add(item1);
return result;
}
function get(url, pdata, func) {
var msg = "Exception";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: url,
data: JSON.stringify(pdata),
dataType: "json",
async: true,
success: function (data, textStatus) {
if (textStatus == "success") {
if (data.hasOwnProperty('d')) {
msg = data.d;
} else {
msg = data;
}
func(msg);
}
},
error: function (data, textStatus) {
get(MEMBERSHIP_SERVICE_AUTHCHCK_URL, {}, function (msg) {
if (msg.error == true) {
window.location = PORTAL_LOGIN_URL;
}
else {
get(url, pdata, func);
}
});
}
});
}
它工作正常。但是当手风琴中的属性为空时。该属性出现在 JSON 字符串中,其值为 null。我希望 System.Web.Script.Services.ScriptService 使用的 JavaScriptSerializer 忽略空属性,因此不在 json 字符串中生成它们。我搜索了很多,我认为 JavaScriptSerializer 不能做到这一点。是否有一种简单的方法来更改 JavaScriptSerializer,例如使用 JSON.net 作为 ScriptService 的默认格式器,或者在序列化为 JSON 时如何忽略生成空属性。