一、操作如下,可以将json对象转为字符串
Json::Value root; root["name"] = "咸鱼"; root["age"] = 100; string str; Json::FastWriter fast; str = fast.write(root); cout << str << endl;
二、实现过程
(1)首先看上面代码,先声明个Value对象root,
Value类中包含以下4个成员变量:
union ValueHolder { Int int_; UInt uint_; double real_; bool bool_; char *string_; ObjectValues *map_; } value_; ValueType type_ : 8; int allocated_ : 1; CommentInfo *comments_;
(2)ObjectVale的原型为typedef std::map<CZString, Value> ObjectValues,以下2句赋值其实是往value_变量中map_中赋值
root["name"] = "咸鱼";
root["age"] = 100;
(3)有了map,j接下来就是把map中的key和value分别拿出来组成有规律的字符串。
FastWriter类中write方法的原型:
FastWriter::write( const Value &root ) { document_ = ""; writeValue( root ); document_ += "\n"; return document_; }
其中writeValue方法的原型:
FastWriter::writeValue( const Value &value ) { switch ( value.type() ) { case nullValue: document_ += "null"; break; case intValue: document_ += valueToString( value.asInt() ); break; case uintValue: document_ += valueToString( value.asUInt() ); break; case realValue: document_ += valueToString( value.asDouble() ); break; case stringValue: document_ += valueToQuotedString( value.asCString() ); break; case booleanValue: document_ += valueToString( value.asBool() ); break; case arrayValue: { document_ += "["; int size = value.size(); for ( int index =0; index < size; ++index ) { if ( index > 0 ) document_ += ","; writeValue( value[index] ); } document_ += "]"; } break; case objectValue: { Value::Members members( value.getMemberNames() ); document_ += "{"; for ( Value::Members::iterator it = members.begin(); it != members.end(); ++it ) { const std::string &name = *it; if ( it != members.begin() ) document_ += ","; document_ += valueToQuotedString( name.c_str() ); document_ += yamlCompatiblityEnabled_ ? ": " : ":"; writeValue( value[name] ); } document_ += "}"; } break; } }
我们可以看到,writeValue方法中,case objectValue部分,
Value::Members members( value.getMemberNames() )这个方法是取出map_变量中的key,然后底下for循环,遍历key对应的value,最后组成字符串document_。