如何在从web方法发出之前操作json字符串

本文关键字:操作 json 字符串 web 方法 | 更新日期: 2023-09-27 18:16:49

我有一个像下面这样的web方法。MyClass是在代理类中定义的,因为它来自另一个外部web服务。

[WebMethod]
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
     public MyClass GetCustomer() 
     {
       MyClass myClass = new MyClass();
       (populate myClass from another web service)
       return myClass;
     }

然而,我不希望MyClass中的所有属性都返回给浏览器。如何排除某些属性?我试图尽量减少json有效载荷,并使其只包括浏览器需要的数据。我不想定义另一个极简类并从MyClass复制内容到它。

如何在从web方法发出之前操作json字符串

只要用scriptignreattribute来装饰你不想序列化的任何属性。

using System;
using System.Web.Script.Serialization;
public class Group
{
    // The JavaScriptSerializer ignores this field.
    [ScriptIgnore]
    public string Comment;
    // The JavaScriptSerializer serializes this field. 
    public string GroupName;
}

你可以试试scriptignreattribute

希望能有所帮助

-

编辑

你可以这样做

[WebMethod]
public MyClass GetCustomer() {
    MyClass myClass = new MyClass() { key = "value", ... };
    return new filteredClass() {filterKey = myClass.value};
}