我有以下代码:
///<summary>
///In this case you can set any other valid attribute for the editable element.
///For example, if the element is edittype:'text', we can set size, maxlength,
///etc. attributes. Refer to the valid attributes for the element
///</summary>
public object OtherOptions { get; set; }
public override string ToString()
{
return this.ToJSON();
}
我需要从OtherOptions属性中获取匿名对象,并像从主对象中一样对匿名对象的每个属性进行序列化。
例如:
OtherOptions = new { A = "1", B = "2" }
如果我将其序列化,它将是(或类似这样的):
OtherOptions: {
A: "1",
B: "2"
}
是否可以在不显式删除的情况下将A和B设置在OtherOptions的相同级别上。
好的,这很丑陋,我不建议您这样做,但是它确实可以满足您的要求。
本质上,它只创建您想要的属性的Dictionary,然后序列化该字典。
static void Main(string[] args)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
var obj = new {Prop1 = "val1", OtherOptions = new {A = "1", B = "2"}};
IDictionary<string, object> result = new Dictionary<string, object>();
foreach (var kv in GetProps(obj))
{
if (!kv.Key.Equals("OtherOptions"))
result.Add(kv);
}
foreach (var kv in GetProps(obj.OtherOptions))
{
result.Add(kv);
}
var serialized = serializer.Serialize(result);
}
static IEnumerable<KeyValuePair<string, object>> GetProps(object obj)
{
var props = TypeDescriptor.GetProperties(obj);
return
props.Cast<PropertyDescriptor>()
.Select(prop => new KeyValuePair<string, object>(prop.Name, prop.GetValue(obj)));
}
序列化为
{"Prop1":"val1","A":"1","B":"2"}
您可以在要忽略的字段上使用属性,然后在GetProps方法中检查该属性,如果存在则不返回。
同样,我不建议您这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句