top of page

Optimizing your JSON Data Access


If you're a .NET developer, you're likely familiar with Newtonsoft's Json.Net framework. Using it makes working with JSON in .NET apps a breeze. Drop in the NuGet package, decorate your model classes, and if the models you're working with are of a reasonable size, you're good to go.

Often when we're working with these models you only need a few properties, yet we serialize the entire model because the performance hit isn't large enough to justify writing new model classes for each subset of properties, along with other work to map data between objects. When performance becomes an issue though, we have a few ways to optimize. Here I'll show how to make use of the LINQ to JSON and ContractResolver features of the framework so you can achieve high performance working with any model, get some code re-use, and keep your model classes tidy.

(You can download the sample app to follow along)

LINQ to JSON

This simple technique can go a long way in the first step of getting your data, as you query only the JSON you're interested in out of the JObject graph. Here we have a Company holding a list of Locations. Each Location has multiple lists of it's own, so deserializing the entire Company when we only want one Location is inefficient and redundant. The following is a simple query to get us the one Location as a JObject in a strongly typed fashion:

Now that we have the JObject we're interested in, we can continue to optimize working with this Location further.

DynamicContractResolver

Have a look at this mobile app used to manage our Location: