0

我正在使用 cJSON 来解析包含键值的字符串。我想动态生成我的结构,为此我需要从这个字符串中读取所有键。

例如,我有一个像下面这样的 json,我想在运行时读取所有键。我不知道json中会出现哪些所有键。

{
    "name": "abc",
    "class": "First",
    "division": "A",
    "age": "10"
}

我如何在不知道键的情况下读取键和值?

我尝试使用指针链接到下一个孩子,但这似乎没有给我正确的值。

cJSON *root = cJSON_Parse(strMyJson);
cJSON *temp = root;

std::cout << "----------" << temp->child->string << "\n";//displays key - correct
std::cout << "----------" << temp->child->valuestring << "\n"; //displays value - correct

//below starts causing problem
temp = temp->child->next;

while (temp != NULL)
{
    std::cout << "----------" << temp->string << "\n";
    std::cout << "----------" << temp->valuestring << "\n";
    temp = temp->child->next;
}

感谢你的帮助 !

-谢谢,小号

4

2 回答 2

0

根 JSON 的结构是这样的:

{ -----------------------------> root  : cJSON_Object 
    "name": "abc",-------------> child : cJSON_String
    "class": "First",----------> child->next : cJSON_String
    "division": "A",-----------> child->next->next : cJSON_String
    "age": "10"----------------> child->next->next->next : cJSON_String
}

打击片段将帮助您了解 cJSON 的工作原理 :)

int main(void)
{
  cJSON *root = cJSON_Parse(jsonstring);
  cJSON *temp = root;
  printf("root item's type--- %d\n", temp->type);      //root item's type is cJSON_Object


  printf("type--- %d\n", temp->child->type);      // cJSON type: 16 cJSON_String; 64 cJSON_Object
  printf("string--- %s\n", temp->child->string);      //displays key - correct
  printf("string--- %s\n", temp->child->valuestring);; //displays value - correct

  temp = temp->child->next;
  char *tempstr = cJSON_Print(temp);
  printf("tempstr = %s\n", tempstr);
  while (temp != NULL)
  {
    printf("type--- %d\n", temp->type);      //displays type - correct
    printf("string--- %s\n", temp->string);      //displays key - correct
    printf("string--- %s\n", temp->valuestring); //displays value - correct
    temp = temp->next;
  }
}
于 2020-04-01T09:03:53.417 回答
0

已解决的问题不知道为什么,但我需要单独处理根案例。

下面的代码有效!

        cJSON *root = cJSON_Parse(strMyJson);
        if(NULL == root)
        {
            std::cout << __func__ << " invalid JSON\n";
            return false;
        }

        cJSON *temp = root;

        temp = temp->child->next;

        std::cout << "value: " << temp->valuestring << "\t";
        std::cout << "key : " << temp->string << "\n";

        temp = temp->next;

        while (temp != NULL)
        {

            std::cout << "----------" << temp->string << "\n";
            std::cout << "----------" << temp->valuestring << "\n";

            temp = temp->next;
        }

-谢谢,小号

于 2019-12-06T05:52:44.453 回答