c++算法使用json输出最终结果给java使用,于是,开始了json对象的组装之旅...
首先,对不同数据类型,封装不同的数据组装函数文章源自IT老刘-https://wp.itlao6.com/731.html
/**
* 拼接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组装,增加 { }及,分隔符文章源自IT老刘-https://wp.itlao6.com/731.html
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("}");
}
c++基础(一):string转wstring及文件拷贝原文:简书ThinkinLiu 博客: IT老五文章源自IT老刘-https://wp.itlao6.com/731.html
c++基础(二):字符串替换及文件路径截取文件名
c++基础(三):数组自增处理及字符串转int,double
c++基础(四):int转string及数组默认值
c++基础(五):文件逐行读取,并根据字符分割数据
c++基础(六):matlab时间转换,ascii转char及时间格式转换文章源自IT老刘-https://wp.itlao6.com/731.html 文章源自IT老刘-https://wp.itlao6.com/731.html
继续阅读
![weinxin](/wp-content/uploads/2023/01/20230117162752-c0a00.jpeg)
我的微信公众号
微信扫一扫关注公众号,不定时更新
评论