Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.Net - Serialize "compressing"?

Tags:

json

c#

.net

Around here, it's very common to create POCOs with long properties names, such as "WarnIfAnyAmountInDebtLongerThan30Days", and some lists have up to 1k items which results on a 1MB Json to be cached/transferred...
I was wondering if there's a way to tell JSON.Net to, instead of serializing with that huge property name, compress it as "P1" (for example), creating some sort of internal dictionary for later deserialization...

Is this possible? or do I have to go to plan B and create another POCO with reduced property names and use a mapper to go back-forth...

EDIT 1:
Creating an alias is not what I want because I have thousands of javascripts and other moving parts depending on that property name... I would like to "compress" it only when serializing for caching!

like image 811
Leonardo Avatar asked Dec 01 '25 07:12

Leonardo


1 Answers

You can decorate your POCOs with the JsonProperty attribute and specify the field name that should be used in the Json...

    [JsonProperty("S1")]
    public string SomeReallyVeryLongName {get; set;}
}

Documentation: https://www.newtonsoft.com/json/help/html/JsonPropertyName.htm

It would have to do be done on all your POCOs, but it's a one-off, consistent, predictable and machine-readable.

If you've got a lot of classes to decorate, you could use something like Fody or PostSharp to do it for you.

like image 52
Basic Avatar answered Dec 02 '25 20:12

Basic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!