Json   发布时间:2022-04-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Simple Class Serialization With JsonCpp大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

A recent project of mine necessitated that I find a way to share data between a client application written in C++ and a host application written in C#. After talking with the other progrAMMer on the project,we decided that usingJson to share data between the applications would be the best solution. This sent me on a search for a decent API for parsingJson data,which led toJsonCpp.

A cursory glance led me to conclude that this API would likely provide me with everything I would need for object serialization. The problem,however,was coming up with a decent design that would allow for full featured serialization. The goals were simple. I needed to be able to serialize and deserialze a class. I would also need access to all data members,including primitives,data structures,and nested classes.

JsonCpp provides us with the capability to do this with relative ease. As such,I hope to provide you all with a basic design to accomplish this. Luckily,we won’t need a deep understanding of JsonCpp to accomplish our goals. As such,I’m not going to overly explain much of the JsonCpp concepts,as the JsonCpp documentation is a good enough @R_489_5550@e.

First,let’s consider a simple test class.

1
2
3
4
5
6
7
8
9
10
11
12
class TESTClassA
{
public :
TESTClassA( void );
virtual ~TESTClassA( void );
private :
int @H_809_45@m_nTesTint;
double @H_809_45@m_fTestFloat;
std::string m_TestString;
bool @H_809_45@m_bTESTBool;
};

This class should provide us with a basic framework to test serialization. We’re going to start with primitive data first (granted,std::string isn’t Strictly primitive,but it’s primitive enough).

Now that we have a basic test case,lets design a basic interface that all of our serializable classes can inherit from.

1
2
3
4
5
6
7
class IJsonserializable
{
public :
virtual ~IJsonserializable( void ) {};
virtual void serialize( Json::Value& root ) =0;
virtual void Deserialize( Json::Value& root) =0;
};

This should be self explanitory. We obvIoUsly need to includejson.h in order to have access to theJson::Value class. The Json::Value class is actually fairly complex,and as such we aren’t going to spent much time examining it. Suffice to say,we are going to treat it as a sort of map,mapping our Metadata tags to the actual values we will be serializing. This will make much more sense once we work on the implementation of the serialize() and Deserialize() methods in our classes.

So let’s update our updated test class deFinition.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class TESTClassA : public IJsonserializable
{
public :
TESTClassA( void );
virtual ~TESTClassA( void );
virtual void serialize( Json::Value& root );
virtual void Deserialize( Json::Value& root);
private :
int @H_809_45@m_nTesTint;
double @H_809_45@m_fTestFloat;
std::string m_TestString;
bool @H_809_45@m_bTESTBool;
};

Now before we progress further on the C++ side of things,let’s cook up some testJson data to work with.

1
2
3
4
5
6
{
"TESTBoolA" : true ,
"testfloatA" : 3.14159 ,
"tesTintA" : 42 ,
"testStringA" : "foo"
}

Whether you kNowJson or not,this data structure should be completely self-explanatory. The goal here is going to be to deserialize this data into our class. However,we have one more thing to do.

The last class we need to design here is the actual serializer class.

1
2
3
4
5
6
7
8
9
class CJsonserializer
{
public :
static bool serialize( IJsonserializable* pObj,std::string& output );
static bool Deserialize( IJsonserializable* pObj,std::string& input );
private :
CJsonserializer( void ) {};
};

This is a simple little “static class”. We’ll make the constructor private this way we can’t actually instantiate it. We will simply deal with the methods directly. This will let us add a second layer of abstraction to JsonCpp.

Alright,our basic design is done. Let’s get into the implementation. Let’s start with our test class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void TESTClassA::serialize( Json::Value& root )
{
// serialize primitives
root[ @H_819_607@"tesTintA" ] = m_nTesTint;
root[ @H_819_607@"testfloatA" ] = m_fTestFloat;
root[ @H_819_607@"testStringA" ] = m_TestString;
root[ @H_819_607@"TESTBoolA" ] = m_bTESTBool;
}
void TESTClassA::Deserialize( Json::Value& root )
{
// deserialize primitives
@H_809_45@m_nTesTint = root.get( @H_819_607@"tesTintA" ,0).asInt();
@H_809_45@m_fTestFloat = root.get( @H_819_607@"testfloatA" ,0.0).asDouble();
@H_809_45@m_TestString = root.get( @H_819_607@"testStringA" , @H_819_607@"" ).asString();
@H_809_45@m_bTESTBool = root.get( @H_819_607@"TESTBoolA" , false ).asBool();
}

Remember when I said we were going to look at theJson::Value class like a map? That should make more sense Now. The serialize() method should make sense. We are simply adding the values to our root object as if it was a map. The keys we are using map directly to the Metadata in theJson data. The Deserialize() method is only slightly more complex. We need to use the get() method in order to retrieve our data. The get() method takes two parameters: get( <key>,<DefaultValue>). KNowing that,the method should make sense. We simply call get() with each key and place the values from theJson into our members.

Now let’s move on to the CJsonserializer class implementation.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
bool CJsonserializer::serialize( IJsonserializable* pObj,std::string& output )
{
if (pObj == NULL)
return false ;
Json::Value serializeRoot;
pObj->serialize(serializeRoot);
Json::StyledWriter writer;
output = writer.write( serializeRoot );
return true ;
}
bool CJsonserializer::Deserialize( IJsonserializable* pObj,std::string& input )
{
if (pObj == NULL)
return false ;
Json::Value deserializeRoot;
Json::reader reader;
if ( !reader.parse(input,deserializeRoot) )
return false ;
pObj->Deserialize(deserializeRoot);
return true ;
}

It should be obvIoUs Now why we wanted a second level of abstraction from JsonCpp.

Let’s look at the serialize() method here. We need to pass two parameters,a pointer to the IJsonserializable object to be serialized,and a reference to a std::string. That String is going to hold the serializedJson data from our class. This is very rudimentary. Wesimply create an instance of aJson::Value object to act as our root,and pass it to the serialize() method of the object in question. That serialize() method will fill theJson::Value object with all of the serialized data. We then create an instance ofJson::StyledWriter,and use it to write theJson data to the emptystd::string we originally passed.

As for the Deserialize() method,it’s not terribly different aside from the fact that the std::string we pass is going to contain Json instead of being empty. We will create an instance ofJson::reader and use it to parse our input String and fill a Json::Value object for us. We will then use that newJson::Value object and pass it to the IJsonserializable objects Deserialze() method,which will set the data members based on theJson::Value object’s values.

As you can see,this is all pretty simple. We can Now create a simple test case.

1
2
3
4
5
6
7
8
9
10
TESTClassA TESTClass;
std::string input = @H_819_607@"{ \"tesTintA\" : 42,\"testfloatA\" : 3.14159,\"testStringA\" : \"foo\",\"TESTBoolA\" : true }\n" ;
CJsonserializer::Deserialize( &TESTClass,input );
std::cout << @H_819_607@"Raw Json Input\n" << input << @H_819_607@"\n\n" ;
std::string output;
CJsonserializer::serialize( &TESTClass,output);
std::cout << @H_819_607@"TESTClass serialized Output\n" << output << @H_819_607@"\n\n\n" ;

If everything went according to plan,you should see the following:

1
2
3
4
5
6
7
8
9
10
Raw Json Input
{ @H_819_607@"tesTintA" : 42, @H_819_607@"testfloatA" : 3.14159, @H_819_607@"testStringA" : @H_819_607@"foo" , @H_819_607@"TESTBoolA" : true }
TESTClass serialized Output
{
@H_819_607@"TESTBoolA" : true ,
@H_819_607@"testfloatA" : 3.14159,
@H_819_607@"tesTintA" : 42,
@H_819_607@"testStringA" : @H_819_607@"foo"
}

Essentially our test case simply created an “empty” TESTClass object. It then deserialized a String of inputJson data into the class,filling it’s members. We then create a new empty output String,and deserialize our TESTClass object into that String. If the outut is what we expect,then we can assume that basic serialization and deserialization is working!

http://www.danielsoltyka.com/programming/2011/04/15/simple-class-serialization-with-jsoncpp/

P.s. complete code:

//#include <cstdlib>
//#include <fstream>
#include <iostream>
#include "json/json.h"


class IJsonserializable
{
  public:
    virtual ~ IJsonserializable (void)
    {
    };
    virtual void serialize (Json::Value & root) = 0;
    virtual void Deserialize (Json::Value & root) = 0;
};


class TESTClassA : public IJsonserializable
{
  public:
    TESTClassA ();
      virtual ~ TESTClassA (void)
    {
    }
    virtual void serialize (Json::Value & root);
    virtual void Deserialize (Json::Value & root);

  private:
    int m_nTesTint;
    double m_fTestFloat;
    std::string m_TestString;
    bool m_bTESTBool;
};

TESTClassA::TESTClassA()
{
    m_nTesTint = 42;
    m_fTestFloat = 3.14159;
    m_TestString = "foo";
    m_bTESTBool = true;
}

void
TESTClassA::serialize (Json::Value & root)
{
    // serialize primitives
    root["tesTintA"] = m_nTesTint;
    root["testfloatA"] = m_fTestFloat;
    root["testStringA"] = m_TestString;
    root["TESTBoolA"] = m_bTESTBool;
}

void
TESTClassA::Deserialize (Json::Value & root)
{
    // deserialize primitives
    m_nTesTint = root.get ("tesTintA",0).asInt ();
    m_fTestFloat = root.get ("testfloatA",0.0).asDouble ();
    m_TestString = root.get ("testStringA","").asString ();
    m_bTESTBool = root.get ("TESTBoolA",falsE).asBool ();
}

class CJsonserializer
{
  public:
    static bool serialize (IJsonserializable * pObj,std::string & output);
    static bool Deserialize (IJsonserializable * pObj,std::string & input);

  private:
      CJsonserializer (void)
    {
    };
};

bool
CJsonserializer::serialize (IJsonserializable * pObj,std::string & output)
{
    if (pObj == NULL)
	return false;

    Json::Value serializeRoot;
    pObj->serialize (serializeRoot);

    Json::StyledWriter writer;
    output = writer.write (serializeRoot);

    return true;
}

bool
CJsonserializer::Deserialize (IJsonserializable * pObj,std::string & input)
{
    if (pObj == NULL)
	return false;

    Json::Value deserializeRoot;
    Json::reader reader;

    if (!reader.parse (input,deserializeRoot))
	return false;

    pObj->Deserialize (deserializeRoot);

    return true;
}


int
main (void)
{
    TESTClassA TESTClass;
    std::string input =
	"{ \"tesTintA\" : 42,\"TESTBoolA\" : true }\n";
    CJsonserializer::Deserialize (&TESTClass,input);

    std::cout << "Raw Json Input\n" << input << "\n\n";

    std::string output;
    CJsonserializer::serialize (&TESTClass,output);

    std::cout << "TESTClass serialized Output\n" << output << "\n\n\n";
    return 0;
}

大佬总结

以上是大佬教程为你收集整理的Simple Class Serialization With JsonCpp全部内容,希望文章能够帮你解决Simple Class Serialization With JsonCpp所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。