Friday 20 April 2012

JSON Data Binding with JSON Spirit

JSON is, like XML, a human readable, text-based format for data representation.

JSON document represents either object or an array.

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:

  1. Download and unpack master from http://gitorious.org/json-spirit/json-spirit/trees/master
  2. Find and open provided Visual Studio solution file (convert it to VS2010 format if necessary). It contains projects: json_demo, json_headers_only_demo, json_map_demo, json_spirit_lib and json_test.
  3. 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.
  4. 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.
  5. Use main.cpp provided below which contains couple of functions that demonstrate JSON/C++ serialization/deserialization:
main.cpp:


Output:
Serialization result (generated JSON string):

{
   "name" : "Fyodor",
   "surName" : "Dostoyevsky"
}

Deserialization result:

name: Fyodor
surName: Dostoyevsky

Serialization result (generated JSON string):

{
   "author" : {
      "name" : "Fyodor",
      "surName" : "Dostoyevsky"
   },
   "isbn" : 123456789,
   "title" : "Crime and Punishment",
   "type" : 1
}

Deserialization result:

author name: Fyodor
author surName: Dostoyevsky
isbn: 123456789
title: Crime and Punishment
type: 1


Links and References:
The application/json Media Type for JavaScript Object Notation (JSON) - RFC 4627
Can a JSON start with [? (SO)

2 comments:

Unknown said...

What is the defination of write_formatted();

Unknown said...

What is the Object obj_auth1; which Object you r refering to.