65.9K
CodeProject is changing. Read more.
Home

ATL with COM Native C++ JSON (de)serializer

starIconstarIconemptyStarIconemptyStarIconemptyStarIcon

2.00/5 (1 vote)

May 10, 2014

CPOL
viewsIcon

19555

downloadIcon

227

Deserialization and serialization classes for JSON objects in native C++ with COM and ATL

Introduction

Microsoft provides JSON parsing capability in .NET but those wishing to do ATL Server programming will have to roll their own. These classes address that issue.  They solve the generic types of JavaScript using COM objects including VARIANT and SAFEARRAY.

Background

One should be familiar with ATL, COM, C++, JSON and server-side programming.

Using the Code

Deserialization example (assuming in a CRequestHandlerT<> derived class):

_tavariant_t varDeserialized;
CAtlMap<CStringW, VARIANT, CStringElementTraitsI<CStringW>>* dictionary;
JavaScriptObjectDeserializer::BasicDeserialize(varDeserialized, 
((CStringA)m_HttpRequest.FormVars.GetKeyAt(pos)).GetBuffer(), c_DefaultRecursionLimit);
if (varDeserialized.vt == (VT_BYREF | VT_UNKNOWN)) {
    dictionary = &((_tavariant_t::DictionaryVariant*)V_BYREF(&varDeserialized))->Dictionary;
}

Serialization example (assuming in a CRequestHandlerT<> derived class):

_tavariant_t varDeserialized;
CAtlArray<CStringW> varArray;
if (AtlArrayToVariant<CStringW>(varDeserialized, varArray) {
    m_HttpResponse << JavaScriptSerializer::SerializeInternal(varDeserialized);
}

Points of Interest

This is based off older .NET 2.0 JSON serialization code and could be updated with any improvements since then. Reflector and decompilation of the .NET libraries allowed for a decent translation though many of the native .NET objects had to use C++ equivalents and the translation is quite large given the nature of C++ is quite different.

History

  • Initial version