如何忽略来自asmx的JSON响应中的空值 - c#

我有返回JSON的简单asmx:

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class myWebService: System.Web.Services.WebService
    {

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public MyCustomClassObject GetTestData()
    {
        MyCustomClassObject x = new MyCustomClassObject();
        x.PropertyA = "1";
        x.PropertyC = "1";
        return x;
    }

C#类定义:

 public class MyCustomClassObject 
    {
        public string PropertyA { get; set; }
        public string PropertyB { get; set; }
        public string PropertyC { get; set; }
        public object PropertyD { get; set; }
    }

使用jquery $ .ajax调用:

 var jqxhr = $.ajax(
                {
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: "/WebServices/myWebService.asmx/GetTestData",
                    data: parameters,
                    dataType: "json",
                    success: successLoadingData,
                    error: errorLoadingData,
                    complete: function () { $("#LoadingImage").hide(); }
                });

我的JSON响应(带有不需要的null值):

{“ PropertyA”:“ 1”,“ PropertyB”:null,“ PropertyC”:“ 1”,“ PropertyD”:null}

题:
如何使用已获得的尽可能多的值仅在JSON中仅获取非null属性?

我在这里看到了一些答案,那里的人们正在返回JSON对象和使用JSON属性定义的属性,但是我只是返回对象,而网络服务为我将其转换为JSON(由于Response.Format属性)。如果需要的话,我将改变我的方法,但是它是我的第一个JSON项目,因此希望保持简单。谢谢。

参考方案

从评论部分继续。
即使您调用函数来删除null值,我个人对此的看法也仍然是它的设计不好,拥有字典和序列化比从我们删除后不需要的属性中移除的更优雅的方法完成。

我要做的是这样的:

public class MyCustomClassObject 
{
    public Dictionary<string, object> Foo { get; set; }

    public MyCustomClassObject()
    {
        this.Foo = new Dictionary<string, object>();
    }

}

public MyCustomClassObject GetTestData()
{
    MyCustomClassObject x = new MyCustomClassObject();
    x.Foo.Add("PropertyA", 2);
    x.Foo.Add("PropertyC", "3");
    return x.Foo;
}

这使您可以使用更通用的对象,并且更好地遵循JSON格式,因为从理论上讲,您可以将对象列表或数组作为值,因此,由于可以在此处添加PropertyD,因此也更适合使用。

添加值后,为什么需要一些删除值的东西?

JSON PATH字段NULL检查表达式 - java

我有一个像bellow的json数组:{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sa…

json_encode的特定方式 - php

所以这是我的PHP<?php include 'connect.php'; $sql = "SELECT name from startup_schema"; $result = mysqli_query($mysqli, $sql) or die("Error in Selecting " …

json_encode网址失败 - php

有人在this bug附近吗?echo json_encode(array('url'=>'/foo/bar')); {"url":"\/foo\/bar"} 我使用Zend_Json and Zend_Json_Expr以便我甚至可以在js对象中获取回调函数-但我无法获得…

json.dumps弄乱顺序 - python

我正在使用json module创建一个包含类似条目的json文件json.dumps({"fields": { "name": "%s", "city": "%s", "status": "%s", "cou…

JSON SCHEMA PATTERN逗号分隔列表 - python

我的json模式中具有以下模式,并且我需要根据以下模式包含逗号分隔的值。当前模式只能像DV2一样处理一种模式所以我应该如何修改我的模式以包括多个字符串,如下所示,但它应该与声明的模式匹配。例如:“ DV2”,“ DEV1”,“ DEV3”,“ ST”, "ENVIRONMENT": { "type": "st…