0

我正在使用类似的东西:

var users = somelinqquery;

目前,我正在使用以下方法返回序列化用户:

    return new JavaScriptSerializer().Serialize(
     new { Result = true, Users = users }
    );

User 对象有更多我需要序列化的属性、年龄、生日等...

如何选择要序列化的属性,例如:

    return new JavaScriptSerializer().Serialize(
     new { Result = true, Users = new { Id = users.id, Name = users.name } }
    );
4

2 回答 2

2

ScriptIgnore属性添加到您的字段/属性

public class User
{
    [ScriptIgnore]
    public string IgnoreThisField= "aaa";
    public string Name = "Joe";
}
于 2012-04-12T20:55:52.467 回答
1

您可以为此特定类型创建自己的JavaScriptConverter 。

通过覆盖IDictionary<string, object> Serialize(object, JavaScriptSerializer),您将仅包含那些需要转换的值。

IEnumerable<Type> SupportedTypes将确保仅将您指定的类型传递给此方法。

编辑

我正在添加一个代码片段来说明我的观点。

public class Foo {
    public String FooField { get; set; }
    public String NotSerializedFooString { get; set; }
}
public class FooConverter : JavaScriptConverter {
    public override Object Deserialize(IDictionary<String, Object> dictionary, Type type, JavaScriptSerializer serializer) {
        throw new NotImplementedException();
    }

    public override IDictionary<String, Object> Serialize(Object obj, JavaScriptSerializer serializer) {
        // Here I'll get instances of Foo only.
        var data = obj as Foo;

        // Prepare a dictionary
        var dic = new Dictionary<String, Object>();

        // Include only those values that should be there
        dic["FooField"] = data.FooField;

        // return the dictionary
        return dic;
    }

    public override IEnumerable<Type> SupportedTypes {
        get {
            // I return the array with only one element.
            // This means that this converter will be used with instances of
            // only this type.
            return new[] { typeof(Foo) };
        }
    }
}
于 2012-04-12T20:57:35.850 回答