Am 07.12.2012 15:00, schrieb Jean-Michel Caricand:

Hello,

I have a Foo class and I can serialize it with JsonSerializer class :

{"integer":1,"str":"str1"}


Now, I want to add an extra field ("other" for example) :

{"integer":1,"str":"str1", other: "10.5"}


How can I do that ?

Thanks,

Jean-Michel

#include <iostream>
#include <sstream>
#include <cxxtools/jsonserializer.h>
#include <cxxtools/jsondeserializer.h>

class Foo {
public:
      int integer;
      std::string str;
};

void operator<<= (cxxtools::SerializationInfo& si, const Foo& obj)
{
      si.addMember("integer") <<= obj.integer;
      si.addMember("str") <<= obj.str;
}

void operator>>= (const cxxtools::SerializationInfo& si, Foo& obj)
{
      si.getMember("integer") >>= obj.integer;
      si.getMember("str") >>= obj.str;
}

int main()
{

      {
          std::stringstream is;
          Foo foo1;

          foo1.integer = 1;
          foo1.str = "str1";

          cxxtools::JsonSerializer s(is);
          s.serialize(foo1);

          // HOWTO TO ADD ANOTHER FIELD ?
           "other" = 10.5;

          s.finish();

          std::cout << is.str() << std::endl;
      }

      return 0;
}
Just add it into your class and serialization operator:

class Foo {
public:
     int integer;
     std::string str;
     std::string other;
};

void operator<<= (cxxtools::SerializationInfo& si, const Foo& obj)
{
     si.addMember("integer") <<= obj.integer;
     si.addMember("str") <<= obj.str;
     si.addMember("other") <<= obj.other;

}

void operator>>= (const cxxtools::SerializationInfo& si, Foo& obj)
{
     si.getMember("integer") >>= obj.integer;
     si.getMember("str") >>= obj.str;
     si.getMember("other") >>= obj.other;
}

You can't modify the generated json string afterwords.

Btw. You can serialize to cout directly and may want to use beautify for debugging like this:

     cxxtools::JsonSerializer s(std::cout);
     s.beautify(true);
     s.serialize(foo1);
     s.finish();


Tommi
------------------------------------------------------------------------------
LogMeIn Rescue: Anywhere, Anytime Remote support for IT. Free Trial
Remotely access PCs and mobile devices and provide instant support
Improve your efficiency, and focus on delivering more value-add services
Discover what IT Professionals Know. Rescue delivers
http://p.sf.net/sfu/logmein_12329d2d
_______________________________________________
Tntnet-general mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/tntnet-general

Reply via email to