jquery - 转换为 JSON 时忽略 null 属性

标签 jquery json asmx

我有一个问题,看起来很简单,但结果却很难。

我写过这样的东西

[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);
            }
        });
    }
});
}

效果很好。但是当 Accordion 中的属性为空时。该属性出现在 JSON 字符串中,其值为 null。我想要 System.Web.Script.Services.ScriptService 使用的 JavaScriptSerializer 忽略 null 属性,因此不会在 json 字符串中生成它们。我搜索了很多,我认为 JavaScriptSerializer 不能做到这一点。有没有一种简单的方法可以更改 JavaScriptSerializer,例如使用 JSON.net 作为 ScriptService 的默认格式化程序,或者如何在序列化为 JSON 时忽略生成 null 属性。

最佳答案

  1. 使用 http://json.org/ 中的 C# 库将对象转换为 json 字符串
  2. 从服务器发送 json 字符串。
  3. 在客户端使用 var obj = $.parseJSON(jsonString);

关于jquery - 转换为 JSON 时忽略 null 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10954397/

相关文章:

jquery - 如何在滚动时突出显示导航的事件状态?

json - 呈现为JSON时Grails中缺少方法异常

.net - 命名空间的 WSDL 仍在使用 "tempuri.org"

c# - 在 ASMX 服务中限制来自不同设备的并发登录

jquery - 如何设置发生任何更改时退出弹出窗口并尝试移动到其他页面

jquery - 确定 Bootstrap Collapse-table 元素的折叠状态

c# - 反序列化保留本地时间的日期

python - 在 Python 中将 JSON 字符串转换为图像

c# - 在 C# 中使用可选参数从 Web 引用调用 WebMethod

javascript - 将 img src 替换为 data-img