I have code structured like below.
public class Stats
{
public string URL { get; set; }
public string Status { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int Length { get; set; }
}
and
public class UrlStats
{
public string URL { get; set; }
public int TotalPagesFound { get; set; }
public List<Stats> TotalPages { get; set; }
public int TotalTitleTags { get; set; }
public List<Stats> TotalTitles { get; set; }
public int NoDuplicateTitleTags { get; set; }
public List<Stats> DuplicateTitles { get; set; }
public int NoOverlengthTitleTags { get; set; }
public List<Stats> OverlengthTitles { get; set; }
}
Basically i am scanning a website for statistics like title tags, duplicate titles, etc.
I am using JQuery and making AJAX calls to webservice and retrieving url stats while the process is running to show user url stats by far collected since it takes quite a time to scan a big website. So after every 5 seconds i retrieve stats from server. Now the problem is all the List variable data i need to send at the end when scanning processing is complete, not during updates. What’s happening right now the List<Stats> variable data is also sent during updates which is big chunk of data and i want to send only int type variables which are required to show process updates.
From searching on internet i couldn’t find anything useful solving my problem and i found that Json.NET is very good library but i really don’t know how to properly use it to get what i want.
Basically i am looking for serializing properties depending on their datatype at runtime, if its possible.
There are two different approaches for your problem.
You should choose the first one if you are going to change your classes more often because the first approach prevents that you forget to serialize a newly added property. Furthermore it is much more reusable if you want to add another classes you want to be serialized the same way.
If you have only these two classes and it’s most likely that they’re not going to change you can choose the second approach to keep your solution simple.
1. Use a custom converter to select all
intpropertiesThe first approach is to use a custom
JsonConverterwhich serializes a class or struct by only including properties which have typeint. The code might look like this:Then you have to decorate your class with a
JsonConverterAttribute:Disclaimer: This code has been tested only very roughly.
2. Choose properties individually
The second solution looks a bit simpler: You can use the
JsonIgnoreAttributeto decorate the attributes you want to exclude for serialization. Alternatively you can switch from “blacklisting” to “whitelisting” by explicitly including the attributes you want to serialize. Here is a bit of sample code:Blacklisting: (I’ve reordered the properties for a better overview)
Whitelisting: (also reordered)