3

This is my Json array.

{
    "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

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.

  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 ?

Smith Dwayne
  • 2,675
  • 8
  • 46
  • 75
  • 1
    It is an array, you need to first get the 2nd element. auto& second_element = user[1]; string name = second_element.GetString(); you can also use iteration by using the user.size() method. – Jonathan May 26 '16 at 12:14

1 Answers1

0

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.

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();
}