typedef struct{
uint8_t key[20];
uint8_t value[200];
}jsonDef;
jsonDef item;
uint8_t jsonData[]="{\"ABC\":22,\"FGH\":{\"III\":11},\"CDE\":\"44\"}";
void Json_Decode(uint8_t* key)
{
uint8_t Findnext = 1;
uint16_t len = sizeof(jsonData);
uint16_t q;
uint8_t shuanyinhaoPoint;
uint8_t keyFound;
uint8_t keyPoint;
uint8_t pointlabel;
uint8_t Includeinto;
for(q=0;q<len;q++)
{
if(shuanyinhaoPoint)
{
if(jsonData[q] == '"')
{
shuanyinhaoPoint--;
}
else
{
item.key[keyPoint] = jsonData[q];
keyPoint++;
}
}
if((jsonData[q] == '"')&&(!keyPoint)&&(Findnext))
{
shuanyinhaoPoint++;
}
if((jsonData[q] == '"')&&(keyPoint))
{
keyPoint = 0;
if(strstr((char*)(item.key),(char*)key))
{
keyFound = 1;
Findnext = 0;
memset(item.key,0,sizeof(item.key));
}
else
{
memset(item.key,0,sizeof(item.key));
Findnext = 1;
}
}
if(keyFound)
{
keyFound++;
}
if(keyFound == 4)
{
pointlabel = jsonData[q];
if(pointlabel == '"')
pointlabel = '"';
else if(pointlabel == '{')
pointlabel = '}';
else
pointlabel = 1;
}
if(keyFound>3)
{
if(pointlabel == '}')
{
if(jsonData[q] == '{')
Includeinto ++;
if(jsonData[q] == '}')
Includeinto --;
item.value[keyFound-4] = jsonData[q];
if((jsonData[q] == pointlabel)&&(Includeinto == 0))
{
keyFound = 0;
pointlabel = 0;
}
}
else if(pointlabel == '"')
{
if(jsonData[q] == '"')
Includeinto ++;
if((jsonData[q] == pointlabel)&&(Includeinto == 2))
{
keyFound = 0;
Includeinto = 0;
pointlabel = 0;
}
if((Includeinto == 1)&&(jsonData[q] != '"'))
item.value[keyFound-5] = jsonData[q];
}
else if(pointlabel == 1)
{
if((jsonData[q] == ',')||(jsonData[q] == '{')||(jsonData[q] == '}'))
{
keyFound = 0;
pointlabel = 0;
}
else
item.value[keyFound-4] = jsonData[q];
}
}
}
}
调用
Json_Decode((uint8_t*)"ABC");
起初本来是想用网上 CJSON 的源码,贯彻能复制黏贴的代码绝不自己写的原则,但是用CJSON源码我只能解析几次JSON数据。网上有人是调大堆栈,我试了下,也只能多解析几次JSON数据。