c++算法使用json输出最终结果给java使用,于是,开始了json对象的组装之旅...
首先,对不同数据类型,封装不同的数据组装函数
/** * 拼接int */std::string getKeyValue(std::string sKey, int iValue){ char szDoubleQutoes[] = "\""; char szColon[] = ":"; char szValue[50] = { 0 }; std::string strResult; strResult.append(szDoubleQutoes); strResult.append(sKey); strResult.append(szDoubleQutoes); strResult.append(szColon); sprintf(szValue, "%d", iValue); strResult.append(szValue); return strResult; }/** * 拼接float,保留3位 */std::string getKeyValue(std::string sKey, float fValue){ char szDoubleQutoes[] = "\""; char szColon[] = ":"; char szValue[50] = { 0 }; std::string strResult; strResult.append(szDoubleQutoes); strResult.append(sKey); strResult.append(szDoubleQutoes); strResult.append(szColon); sprintf(szValue, "%0.3f", fValue); strResult.append(szValue); return strResult; }/** * 拼接string */std::string getKeyValue(std::string sKey, std::string sValue){ char szDoubleQutoes[] = "\""; char szColon[] = ":"; std::string strResult; strResult.append(szDoubleQutoes); strResult.append(sKey); strResult.append(szDoubleQutoes); strResult.append(szColon); strResult.append(szDoubleQutoes); strResult.append(sValue); strResult.append(szDoubleQutoes); return strResult; }/** * 拼接object */std::string getKeyValueObject(std::string sKey, std::string sObject){ char szDoubleQutoes[] = "\""; char szColon[] = ":"; std::string strResult; strResult.append(szDoubleQutoes); strResult.append(sKey); strResult.append(szDoubleQutoes); strResult.append(szColon); strResult.append(sObject); return strResult; }/** * 拼接array */std::string getKeyValueArray(std::string sKey, std::string sArray){ char szDoubleQutoes[] = "\""; char szColon[] = ":"; std::string strResult; strResult.append(szDoubleQutoes); strResult.append(sKey); strResult.append(szDoubleQutoes); strResult.append(szColon); strResult.append("["); strResult.append(sArray); strResult.append("]"); return strResult; }
调用,及最终json组装,增加 { }及,分隔符
int main() { int value1 = 1; float value2 = 1.0f; std::string strJsonResult("{"); strJsonResult.append(getKeyValue("key1", value1)); strJsonResult.append(","); strJsonResult.append(getKeyValue("key2", value2)); strJsonResult.append("}"); }
作者:ThinkinLiu
链接:https://www.jianshu.com/p/4022b807c6e7