How to Not Serialize the _Type Property on JSON Objects

How to exclude property from Json Serialization

If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.

public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }

// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}

Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.

[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }

// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}

Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details

How to exclude specific type from json serialization

The following allows you to exclude a specific data-type that you want excluded from the resulting json. It's quite simple to use and implement and was adapted from the link at the bottom.

You can use this as you cant alter the actual classes:

public class DynamicContractResolver : DefaultContractResolver
{

private Type _typeToIgnore;
public DynamicContractResolver(Type typeToIgnore)
{
_typeToIgnore = typeToIgnore;
}

protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);

properties = properties.Where(p => p.PropertyType != _typeToIgnore).ToList();

return properties;
}
}

Usage and sample:

public class MyClass
{
public string Name { get; set; }
public byte[] MyBytes1 { get; set; }
public byte[] MyBytes2 { get; set; }
}

MyClass m = new MyClass
{
Name = "Test",
MyBytes1 = System.Text.Encoding.Default.GetBytes("Test1"),
MyBytes2 = System.Text.Encoding.Default.GetBytes("Test2")
};

JsonConvert.SerializeObject(m, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver(typeof(byte[])) });

Output:

{
"Name": "Test"
}

More information can be found here:

Reducing Serialized JSON Size

How to deserialize a property on JSON from one type but serialize to another type with the same name?

Thanks to @Fildor for leading me in the right direction.
The answer was deceptively simple, add a type converter and decorate the new property with the converter.

public class Something {
[JsonConverter(typeof(FeeConverter))]
public Fee Fee { get; set;}
}

public class Fee {
public decimal? Amount { get; set; }
public int Type { get; set; }
}

public class FeeConverter : JsonConverter
{

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Float || reader.TokenType == JsonToken.Integer)
{
var property = JValue.Load(reader);
return new Fee() { Amount = property.Value<decimal>() };
}

return serializer.Deserialize(reader, objectType);
}

public override bool CanWrite => false;

public override bool CanConvert(Type objectType) => false;
}

Json.net serialize only certain properties

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


Related Topics



Leave a reply



Submit