c++ - 从 JSON 字符串中获取数组时出错

标签 c++ json libjson

我正在尝试从 main 函数中定义的 JSON Stinrg 中获取数组。我为此使用了 libjson API,简单的键值很容易获得,所以我能够获得 RootA 的值,但是 ChildA 中的这个数组怎么样。请告诉我

#include <iostream>
#include <libjson/libjson.h>
#include <stdio.h>
#include <string.h>

using namespace std;

char rootA[20];
int childB;
int *childInt;

void ParseJSON(JSONNODE *n) {
    if (n == NULL) {
        printf("Invalid JSON Node\n");
        return;
    }

    JSONNODE_ITERATOR i = json_begin(n);
    while (i != json_end(n)) {
        if (*i == NULL) {
            printf("Invalid JSON Node\n");
            return;
        }

        // recursively call ourselves to dig deeper into the tree
        if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE) {
            ParseJSON(*i);
        }

        // get the node name and value as a string
        json_char *node_name = json_name(*i);

        // find out where to store the values
        if (strcmp(node_name, "RootA") == 0) {
            json_char *node_value = json_as_string(*i);
            strcpy(rootA, node_value);
            cout << rootA<<"\n";
            json_free(node_value);
        } else if (strcmp(node_name, "ChildA") == 0) {
            JSONNODE *node_value = json_as_array(*i);

            childInt=reinterpret_cast<int *>(&node_value);
            cout << childInt[0]<<"\n";
            cout << childInt[1]<<"\n";
            json_free(node_value);
        } else if (strcmp(node_name, "ChildB") == 0) {
            childB = json_as_int(*i);
            cout << childB;
        }
        // cleanup and increment the iterator
        json_free(node_name);
        ++i;
    }
}

int main(int argc, char **argv) {
    char
            *json =
                    "{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":[1,2],\"ChildB\":42}}";
    JSONNODE *n = json_parse(json);
    ParseJSON(n);
    json_delete(n);
    return 0;
}

最佳答案

谢谢 not-sehe 但我得到了解决方案

好的,我明白了...将数组视为一个节点并再次迭代它,就好像它是一个带有空白键的值一样。您可以看到执行此操作的代码部分..

if (json_type(*i) == JSON_ARRAY) {
    cout << "\n Its a Json Array";
    JSONNODE *arrayValue = json_as_array(*i);
    JSONNODE_ITERATOR i1 = json_begin(arrayValue);
    while (i1 != json_end(arrayValue)) {
            cout << "\n In Array Loop ";
        cout << json_as_int(*i1);
        ++i1;
    }
}

关于c++ - 从 JSON 字符串中获取数组时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17064905/

相关文章:

libjson - 如何创建 libJSON 库?

c++ - 大小为 4 的迭代器无效读取

javascript - JSON 编码为 Javascript

c++ - 按值、引用和右值传递字符串

javascript - 来自 Angular 的 Http Post 请求不起作用

java - Gson - 根据字段值反序列化为特定对象类型

交叉编译libjson-c : Make unsuccessful in libjson-c, Linkhash.c警告

c++ - 未知错误可能是由命名冲突引起的?

c++ - 多个输入验证约束? C++