views:

492

answers:

2

Is it possible to exclude specified fields at runtime when serializing an object to a JSON string? i.e. When serializing an object, only serialize fields specified in list.

+4  A: 

Any properties that don't have the [DataMember] attribute will not be serialized

[DataContract]
public class MyClass
{
  [DataMember]
  public string SerializeMe {get;set;}

  public string DontSerializeMe {get;set;}

  [DataMember]
  public string SerializeMeToo {get;set;}
}
Jose Basilio
Can i decide programmatically at runtime not to serialize the field "SerializeMe"?
seanlinmt
+1  A: 

The DataContractJsonSerializer is opt-in so only fields with marked with the DataMemberAttribute is included.

I wanted to change this at runtime (as in programmatically exclude certain fields depending on certain conditions) to exclude fields which are null but this is the default behaviour. So I guess it is no longer relevant.

Update, the following could also be used:

public DateTime DateOfBirth;

[DataMember] public bool Confidential;

[DataMember (Name="DateOfBirth", EmitDefaultValue=false)]
DateTime? _tempDateOfBirth;

[OnSerializing]
void PrepareForSerialization (StreamingContext sc)
{
  if (Confidential)
    _tempDateOfBirth = DateOfBirth;
  else
    _tempDateOfBirth = null;
}
seanlinmt