Json.net serialize only certain properties
Rather then having to use [JsonIgnore]
on every attribtue you don't want to serialise as suggested in another answer.
If you just want to specify properties to serialise, you can do this, using [JsonObject(MemberSerialization.OptIn)]
and [JsonProperty]
attributes, like so:
using Newtonsoft.Json;
...
[JsonObject(MemberSerialization.OptIn)]
public class Class1
{
[JsonProperty]
public string Property1 { set; get; }
public string Property2 { set; get; }
}
Here only Property1
would be serialised.
You can write a custom ContractResolver like below
public class IgnoreParentPropertiesResolver : DefaultContractResolver
{
bool IgnoreBase = false;
public IgnoreParentPropertiesResolver(bool ignoreBase)
{
IgnoreBase = ignoreBase;
}
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var allProps = base.CreateProperties(type, memberSerialization);
if (!IgnoreBase) return allProps;
//Choose the properties you want to serialize/deserialize
var props = type.GetProperties(~BindingFlags.FlattenHierarchy);
return allProps.Where(p => props.Any(a => a.Name == p.PropertyName)).ToList();
}
}
Now you can use it in your serialization process as:
var settings = new JsonSerializerSettings() {
ContractResolver = new IgnoreParentPropertiesResolver(true)
};
var json1 = JsonConvert.SerializeObject(new SubObjectWithOnlyDeclared(),settings );