Friday, 20 April 2012

JSON Data Binding with JSON Spirit

Object starts and ends with curly brackets ({ }) and contains zero or more key-value pairs. Key (or name) is a string and value can be another object, number, string, array or literal true, false or null. Key is separated from value with a single colon (:). Key-value pars are separated with commas (,).

Array starts and ends with square brackets ([ ]) and contains zero or more values.

I wrote a mini series of articles on XML Data Binding and in this article I want to show how to serialize C++ object to JSON document and how to perform reverse process - how to deserialize JSON document back to the object.

JSON parser I am using here is JSON Spirit. Here is the list of steps of how to get working example from the scratch:

We will create test project that will be using JSON Spirit static library and its headers (Boost headers will be necessary as well). Build json_spirit_lib project which output is static library named json_spirit_lib.lib.

In Project Settings for our test project, add json_spirit_lib.lib to Additional Dependencies as well as path to JSON Spirit headers (path to json_spirit directory) and path to Boost.

Use main.cpp provided below which contains couple of functions that demonstrate JSON/C++ serialization/deserialization: