0

私は次のようなものを使用しています:

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 } }
    );
4

2 に答える 2

2

ScriptIgnoreフィールド/プロパティに属性を追加します

public class User
{
    [ScriptIgnore]
    public string IgnoreThisField= "aaa";
    public string Name = "Joe";
}
于 2012-04-12T20:55:52.467 に答える
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) };
        }
    }
}
于 2012-04-12T20:57:35.850 に答える