如何使用C ++中的rapidjson库从json格式字符串中获取值

时间:2015-04-30 02:08:00

标签: c++ json rapidjson

我正在尝试使用C ++中的rapidjson库来迭代以下json格式字符串中的值。我有这个json格式的字符串来响应来自Allegro Graph Server的查询。

json格式如下:

{"names":["s","pred","o"],"values":[["<http://www.example.com/ns/node2>","<http://www.example.com/ns/connectWith>","<http://www.example.com/ns/node5>"],["<http://www.example.com/ns/node3>","<http://www.example.com/ns/connectWith>","<http://www.example.com/ns/node4>"],["<http://www.example.com/ns/node6>","<http://www.example.com/ns/connectWith>","<http://www.example.com/ns/node1>"]]}

我尝试使用rapidjson教程示例迭代他们的示例json字符串,它没有问题。但是当我传递上述数据时,编译器抱怨如下: rapidjson :: GenericValue :: GetInt()const [with Encoding = rapidjson :: UTF8&lt;&gt ;; Allocator = rapidjson :: MemoryPoolAllocator&lt;&gt;]:断言`flags_&amp; kIntFlag&#39;

失败了

我使用以下代码迭代

    // I have added \ before * in the following data to make string
   const char json[]= " {\"names\":[\"s\",\"pred\",\"o\"],\"values\":[[\"<http://www.example.com/ns/node2>\",\"<http://www.example.com/ns/connectWith>\",\"<http://www.example.com/ns/node5>\"],[\"<http://www.example.com/ns/node3>\","<http://www.example.com/ns/connectWith>\",\"<http://www.example.com/ns/node4>\"],[\"<http://www.example.com/ns/node6>\",\"<http://www.example.com/ns/connectWith>\",\"<http://www.example.com/ns/node1>\"]]}";

    printf("Original JSON:\n %s\n", json);
    Document document;  // Default template parameter uses UTF8 and MemoryPoolAllocator.

#if 0
    // "normal" parsing, decode strings to new buffers. Can use other input stream via ParseStream().
    if (document.Parse(json).HasParseError())
        return 1;
#else
    // In-situ parsing, decode strings directly in the source string. Source must be string.
    char buffer[sizeof(json)];
    memcpy(buffer, json, sizeof(json));
    if (document.ParseInsitu(buffer).HasParseError())
        return ;
#endif
    printf("\nParsing to document succeeded.\n");
    // 2. Access values in document.
    printf("\nAccess values in document:\n");
    assert(document.IsObject());    // Document is a JSON value represents the root of DOM. Root can be either an object or array.
    assert(document.HasMember("names"));
      // Using a reference for consecutive access is handy and faster.
    const Value& a = document["names"];
    for (SizeType i = 0; i < a.Size(); i++) // Uses SizeType instead of size_t
            printf("a[%d] = %d\n", i, a[i].GetInt());   

有没有人可以帮我解决一下如何从json字符串中获取值?

预期输出如下.nt文件,一行中的每个数组值都跟随点。

<http://www.example.com/ns/node2> <http://www.example.com/ns/connectWith> <http://www.example.com/ns/node5> .
<http://www.example.com/ns/node3> <http://www.example.com/ns/connectWith> <http://www.example.com/ns/node4> .
<http://www.example.com/ns/node6> <http://www.example.com/ns/connectWith> <http://www.example.com/ns/node1> .

1 个答案:

答案 0 :(得分:1)

const Value& a = document["values"];
StringBuffer buf;
PrettyWriter<StringBuffer> wr(buf);
a.Accept(wr);
const char* js = buf.GetString();