C# 动态序列化

C# 动态序列化,c#,.net,json,C#,.net,Json,我写了一个asp.NETMVC控制器 我向客户端发送JSON作为对操作的响应 { A : "bla", B: "bla2"} 如何根据字段B的值的存在使其成为暂定字段 意思是: 类服务器对象 { A : "bla", B: null} 将作为 { A : "bla"} 这个链接可能会有所帮助 基本上,将c#对象序列化为json,然后可以使用正则表达式查找所有具有null值的属性并删除它们 编辑: 您可以像这样对字符串使用扩展方法 public static string RemoveJs

我写了一个asp.NETMVC控制器

我向客户端发送JSON作为对操作的响应

{ A : "bla", B: "bla2"}
如何根据字段B的值的存在使其成为暂定字段

意思是: 类服务器对象

{ A : "bla", B:  null}
将作为

{ A : "bla"}
这个链接可能会有所帮助

基本上,将c#对象序列化为json,然后可以使用正则表达式查找所有具有null值的属性并删除它们

编辑:

您可以像这样对字符串使用扩展方法

public static string RemoveJsonNulls(this string str)
    {
        if (!str.IsEmptyOrNull())
        {
            Regex regex = new Regex(UtilityRegExp.JsonNullRegEx);
            string data = regex.Replace(str, string.Empty);
            regex = new Regex(UtilityRegExp.JsonNullArrayRegEx);
            return regex.Replace(data, "[]");
        }
        return null;
    }

public static string JsonNullRegEx = "[\"][a-zA-Z0-9_]*[\"]:null[ ]*[,]?";

public static string JsonNullArrayRegEx = "\\[( *null *,? *)*]";
这个链接可能会有所帮助

基本上,将c#对象序列化为json,然后可以使用正则表达式查找所有具有null值的属性并删除它们

编辑:

您可以像这样对字符串使用扩展方法

public static string RemoveJsonNulls(this string str)
    {
        if (!str.IsEmptyOrNull())
        {
            Regex regex = new Regex(UtilityRegExp.JsonNullRegEx);
            string data = regex.Replace(str, string.Empty);
            regex = new Regex(UtilityRegExp.JsonNullArrayRegEx);
            return regex.Replace(data, "[]");
        }
        return null;
    }

public static string JsonNullRegEx = "[\"][a-zA-Z0-9_]*[\"]:null[ ]*[,]?";

public static string JsonNullArrayRegEx = "\\[( *null *,? *)*]";

您可以将其添加到global.asax.cs并尝试:“GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore;”Global.asax的确切位置在哪里?在应用程序的开始部分,或注册路由、依赖项等的任何方法中。是否可以将此添加到Global.asax.cs并尝试:“GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore;”在Global.asax中的确切位置?在应用程序的起始位置,或用于注册路由、依赖项等的任何方法中。