简体   繁体   English

使用rapidjson读取嵌套的Json

[英]Reading Nested Json using rapidjson

This is my Json array. 这是我的Json数组。

{
    "colorsArray":[{
            "colorName":"red",
            "hexValue":"#f00"
        },
        {
            "colorName":"green",
            "hexValue":"#0f0"
        },
        {
            "colorName":"blue",
            "hexValue":"#00f"
        }
    ]
}

I want to get value 'green'. 我希望得到“绿色”的价值。 My c++ code in rapidjson library is 我在rapidjson库中的c ++代码是

Document document;
document.Parse<0>(jsoncontent.c_str()).HasParseError();
document.Parse(jsoncontent.c_str());
const Value& user = document["colorsArray"];
string name = user["colorName"].GetString();

When I try to access the colorName, I am getting the below Runtime error. 当我尝试访问colorName时,我收到以下运行时错误。

  rapidjson::GenericValue<Encoding, Allocator>::MemberIterator 
rapidjson::GenericValue<Encoding, Allocator>::FindMember(const 
rapidjson::GenericValue<Encoding, SourceAllocator>&) [with SourceAllocator
 = rapidjson::MemoryPoolAllocator<>; Encoding = rapidjson::UTF8<>; 
Allocator = rapidjson::MemoryPoolAllocator<>; 
rapidjson::GenericValue<Encoding, Allocator>::MemberIterator = 
rapidjson::GenericMemberIterator<false, rapidjson::UTF8<>, 
rapidjson::MemoryPoolAllocator<> >]: Assertion `IsObject()' failed.

    Aborted (core dumped)

How can I read a particular value using Rapidjson Library ? 如何使用Rapidjson Library读取特定值?

Briefly, in my opinion, the document is incomplete. 简而言之,在我看来,该文件是不完整的。 If you put the reading-value code in a loop body or a thread and run the program, the error would happen when you terminate. 如果将读取值代码放在循环体或线程中并运行程序,则终止时会发生错误。 So, judge the document is IsObject() first when you want to get a value. 因此,当您想要获取值时,首先判断文档是IsObject()。

Maybe this can be work: 也许这可以工作:

Document document;
document.Parse<0>(jsoncontent.c_str()).HasParseError();
document.Parse(jsoncontent.c_str());
if(document.IsObject())        // add this line
{
    const Value& user = document["colorsArray"];
    string name = user["colorName"].GetString();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM