我正在使用类似的东西:
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 } }
);
答案 0 :(得分:2)
将ScriptIgnore
属性添加到您的字段/属性
public class User
{
[ScriptIgnore]
public string IgnoreThisField= "aaa";
public string Name = "Joe";
}
答案 1 :(得分: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) };
}
}
}