如何在不包含属性名称的情况下将匿名对象序列化为JSON

时间:2013-12-19 01:56:13

标签: c# json c#-4.0 javascriptserializer anonymous-objects

我有以下代码:

///<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属性中获取匿名对象,并将匿名对象的每个属性序列化为主对象。

E.g:

OtherOptions = new { A = "1", B = "2" }

如果我序列化它,它将是(或类似的东西):

OtherOptions: {
A: "1",
B: "2"
}

是否可以将A和B置于OtherOptions的相同级别而不显式删除它。

1 个答案:

答案 0 :(得分:2)

好的,这只是丑陋的,我不建议这样做,但它可以做你想要的......

基本上,它只创建一个包含所需属性的字典,然后序列化该字典。

    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方法中检查该属性,如果存在则不返回。

同样,我不建议这样做。