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

C# 如何在不包含属性名的情况下将匿名对象序列化为JSON,c#,json,c#-4.0,javascriptserializer,anonymous-objects,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 eleme

我有以下代码:

///<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();
}
如果我序列化它,它将是(或类似的内容):


有没有可能让A和B处于其他选项的同一级别而不显式删除它。

好的,这很难看,我不建议这样做,但它可以满足您的需要

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

    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)));
    }
您可以在要忽略的字段上使用属性,然后在GetProps方法中检查该属性,如果存在则不返回


同样,我不建议这样做。

简短回答:不。您必须用对象图来欺骗或使用自定义对象序列化。
OtherOptions: {
A: "1",
B: "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"}