/* cjson库的使用 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h> #include "cJSON.h" /*
说明:
组装成json效率并不高,并不推荐json,字符串远比json快,但是字符串表示不了对象,protobuf虽然快,但是依赖于第三方库,很棘手
*/ //数据解析
int testPause(const char * pcJson)
{
cJSON *pstRoot = NULL;
cJSON *pstNode = NULL;
cJSON *pstFeat = NULL;
cJSON *pstArray = NULL;
cJSON *pstAudio = NULL;
cJSON *pstRole = NULL;
cJSON *pstTmp = NULL;
int arraySize = ;
int i = , j = ;
int featSize = ; if (NULL == pcJson)
{
return -;
} //解析json字符串
pstRoot = cJSON_Parse(pcJson);
if (NULL == pstRoot)
{
return -;
} do
{
//获取json对象
pstAudio = cJSON_GetObjectItem(pstRoot, "audio");
if (NULL == pstAudio)
{
printf("--no audio info .---\n");
break;
} //获取字符串型json对象的值
printf("====audio info %s=======\n", pstAudio->valuestring); pstArray = cJSON_GetObjectItem(pstRoot, "array");
if (NULL == pstArray)
{
printf("--no array info .---\n");
break;
} //提取json数组
//1.获取数组长度
arraySize = cJSON_GetArraySize(pstArray);
if ( == arraySize)
{
printf("--no array info .---\n");
break;
} for (i = ; i < arraySize; i++)
{
pstNode = cJSON_GetArrayItem(pstArray, i);
if (pstNode)
{
//获取角色信息
pstRole = cJSON_GetObjectItem(pstNode, "role");
if (NULL == pstRole)
{
printf("--no role info .---\n");
break;
}
printf("====role info %d=======\n", pstRole->valueint); //获取声纹信息
pstFeat = cJSON_GetObjectItem(pstNode, "feat");
if (NULL == pstFeat)
{
printf("--no feat info .---\n");
break;
} //获取声纹长度
featSize = cJSON_GetArraySize(pstFeat);
if ( == featSize)
{
printf("--no feat size info .---\n");
break;
}
for (j = ; j < featSize; j++)
{
pstTmp = cJSON_GetArrayItem(pstFeat, j);
printf("==feat[%lf]==\n", pstTmp->valuedouble);
}
}
} } while (); // 释放资源
if (pstRoot)
{
cJSON_Delete(pstRoot);
pstRoot = NULL;
} return ;
} //数据组装
char * testAssemble(void)
{
cJSON *pstRoot = NULL;
cJSON *pstNode = NULL;
cJSON *pstFeat = NULL;
cJSON *pstArray = NULL;
float aFeat[] = { 1.1f, 2.2f, 3.3f, 4.4f, 5.5f, 6.6f, 7.7f, 8.8f, 9.9f, 0.0f };
char * pOutput = NULL; //创建普通json对象
pstRoot = cJSON_CreateObject();
assert(pstRoot); pstNode = cJSON_CreateObject();
assert(pstNode); //创建float数组类型json对象
pstFeat = cJSON_CreateFloatArray(aFeat, );
assert(pstFeat); cJSON_AddNumberToObject(pstNode, "role", );
cJSON_AddItemToObject(pstNode, "feat", pstFeat); //创建一个json对象数组
pstArray = cJSON_CreateArray();
assert(pstArray); //将一个json对象加入到json数组中
cJSON_AddItemToArray(pstArray, pstNode); //布尔值添加
cJSON_AddStringToObject(pstRoot, "audio", "test.wav");
cJSON_AddItemToObject(pstRoot, "array", pstArray); //输出json字符串(内存需要自己释放)
pOutput = cJSON_Print(pstRoot); // 释放资源
if (pstRoot)
{
cJSON_Delete(pstRoot);
pstRoot = NULL;
} return pOutput; } int main()
{
char * pcJson = NULL; pcJson = testAssemble();
if (NULL == pcJson)
{
printf("----[testAssemble]-----failed-----\n");
return -;
} //打印数据
printf("===%s==\n", pcJson); printf("\n"); //解析json
testPause(pcJson); //释放资源
if (pcJson)
{
free(pcJson);
pcJson = NULL;
} printf("-----ok------\n"); getchar(); return ;
}
05-28 08:52
查看更多