I'm saving JSON objects into the database, sometimes it grows very large (I have an object of length 205,797 characters) I want to eliminate the size as possible as I can. these objects have a lot of GUID fields, all I don't need, It may help eliminating the size if there is a way to ignore any GUID type from serializing.
This is my code, I pass an object of any model type in my application:
public static string GetEntityAsJson(object entity)
{
var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return json;
}
EDIT
I don't want to use JsonIgnore
attribute, as I will have to add it to so many classes each has a lot of GUID properties,
I'm looking for something straight forward like:
IgnoreDataType = DataTypes.GUID
To ignore individual properties, use the [JsonIgnore] attribute. You can specify conditional exclusion by setting the [JsonIgnore] attribute's Condition property. The JsonIgnoreCondition enum provides the following options: Always - The property is always ignored.
JsonSerializationException(String, String, Int32, Int32, Exception) Initializes a new instance of the JsonSerializationException class with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.
JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).
JSON is a format that encodes an object to a string. On the transmission of data or storing is a file, data need to be in byte strings, but as complex objects are in JSON format. Serialization converts these objects into byte strings which is JSON serialization.
You can use a custom ContractResolver
to ignore all properties of a specific data type in all classes. For example, here is one that ignores all Guids
:
class IgnoreGuidsResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (prop.PropertyType == typeof(Guid))
{
prop.Ignored = true;
}
return prop;
}
}
To use the resolver, just add it to your JsonSerializerSettings
:
var json = JsonConvert.SerializeObject(entity, Formatting.None, new JsonSerializerSettings
{
ContractResolver = new IgnoreGuidsResolver(),
...
});
Demo fiddle: https://dotnetfiddle.net/lOOUfq
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With