2

次のコードがあります。

///<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 にすることは可能ですか。

4

1 に答える 1

2

わかりました、これはただ醜いので、私はそれをすることをお勧めしませんが、それはあなたが望むことをします...

基本的に、必要なプロパティだけの 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 メソッドでその属性をチェックし、存在する場合は返さないことができます。

繰り返しますが、これを行うことはお勧めしません。

于 2013-12-19T06:48:06.737 に答える