【问题标题】:How to Ignore class property from Json Serialization如何从 Json 序列化中忽略类属性
【发布时间】:2017-10-27 08:03:28
【问题描述】:

我正在使用 asp.net 4.0 创建一个 web 服务。

我创建了一个 asmx 文件并创建了一个 User.cs 类。它有 8 个属性。 我返回了一个 json 格式的服务。 如果userlogin 为真我需要返回user.cs 的所有属性,如果失败我只需要返回2 个属性。

如何实现。

用户登录为真。它会全部返回

{"message":"有效用户","BranchId":1,"BranchName":"我的分支名称","Id":1,"Name":"admin","密码": "admin","RoleId":1,"Status":1}

用户登录失败,我只需要重新调整消息和状态。但它会像下面一样返回所有内容

{"message":"用户名或密码无效","BranchId":0,"BranchName":null,"Id":0,"Name":null,"Password":null,"RoleId": 0,"状态":0}

我用谷歌搜索并得到以下Link。如何根据我的登录状态使用它。

如果我在我的属性中使用了 [ScriptIgnore],它将忽略两种情况下的属性。登录失败时需要忽略属性。

我的属性是这样的

// Properties
    public int BranchId
    {
        get { return _BranchId; }
        set { if (_BranchId != value) { _BranchId = value; } }
    }

    public string BranchName
    {
        get { return _BranchName; }
        set { _BranchName = value; }
    }

    private String _message;

    public String message
    {
        get { return _message; }
        set { _message = value; }
    }

我的网络服务

[WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public void appLogin(String userName, String passWord)
    {
        Admin_AppUserBLL objusr = Admin_AppUserBLL.GetAdmin_AppUserBLL(userName);
        string strResponse = "";
        if (objusr != null)
        {
            if (objusr.Password == passWord)
            {
                objusr.message = "valid username";
                strResponse = new JavaScriptSerializer().Serialize(objusr);
            }
        }
        else
        {
            objusr = new Admin_AppUserBLL();
            objusr.message = "username or password is invalid";
            strResponse = new JavaScriptSerializer().Serialize(objusr);
        }
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.AddHeader("content-length", strResponse.Length.ToString());
        Context.Response.Flush();
        Context.Response.Write(strResponse);
    }

【问题讨论】:

  • 请检查here - 可能重复

标签: c# asp.net json web-services


【解决方案1】:

在您的属性上添加以下属性,并使用“?”使其可以为空

[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "BranchId")]
        public int? BranchId{ get; set; }

如果 value 为 null 并且 json 不包含这些人,它将忽略。

【讨论】:

  • 它显示以下错误,找不到类型或命名空间名称“JsonProperty”(您是否缺少 using 指令或程序集引用?
  • 在您的应用程序中添加 NewtonSoft 的引用。如果解决了您的问题,请标记解决方案。
  • @Hisanth 使用的是 JavaScriptSerializer 而不是 NewtonSoft
  • 它是 Json.net 的一部分 参考以下链接newtonsoft.com/json/help/html/JsonPropertyName.htm
【解决方案2】:

在 Newtonsoft 中添加引用

using Newtonsoft.Json;

同时序列化对象

string strResponse = JsonConvert.SerializeObject(objusr, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });

它会避免空值属性

【讨论】:

    猜你喜欢
    • 2019-08-02
    • 2015-01-12
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-02
    相关资源
    最近更新 更多