user1936508
user1936508

Reputation: 59

Parsing JSON arrays in C++

I am writing a server-client program. The server is written in C++ and I use JSON strings to send the data. This library helps me a lot and everything works, but I have one question: How can I parse a JSON array of strings to a normal C++ array? I searched for methods in the documentation, but didn't find any. Do I have to write my own function?

Example, where s is the JSON string {"msg":"message", "content":["content1", "content2"]}:

CJsonObject *obj = CJsonParser::Execute(s); 
string msg = (*obj)["msg"]->ToString();
string content = (*obj)["content"]->ToString();
cout << msg << endl; // message
cout << content << endl; // ["content1", "content2"]

But I want an array/vector of "content1", "content2".

Upvotes: 1

Views: 16314

Answers (3)

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

It looks like CJsonObject::operator[] returns a const CJsonValue* which may point at an object with dynamic type CJsonArray. That is (*obj)["content"] returns a pointer to an object of type CJsonArray. You can do a dynamic_cast<CJsonArray*> to make sure.

CJsonArray has a member function called GetValue which takes an std::vector<CJsonValue*> by reference and fills it up with the values from the array.

So you can do something like (untested):

if (auto array = dynamic_cast<const CJsonArray*>((*obj)["content"])) {
  std::vector<CJsonValue*> vec;
  array->GetValue(vec);
  for (auto& value : vec) {
    std::cout << value->ToString() << std::endl;
  }
}

Or the C++03 equivalent:

if (const CJsonArray* array = dynamic_cast<const CJsonArray*>((*obj)["content"])) {
  typedef std::vector<CJsonValue*> ValueVector;
  ValueVector vec;
  array->GetValue(vec);
  for (ValueVector::iterator it = vec.begin(); it != vec.end(); it++) {
    std::cout << (*it)->ToString() << std::endl;
  }
}

Upvotes: 2

BAK
BAK

Reputation: 1005

You can check the real type of a Json Object and use a cast for retreving a CJsonArray object.

After the dynamic cast, your object resulting is a CJsonArray, wich has a method for that: getValue.

if (content.getType() == JV_ARRAY) {
  std::vector <CJsonValue*> values;

  (dynamic_cast<CJsonArray*>(content))->getValue(values);

}

The value vector contain CJsonValue, so you can use ToString() for each elements.

Upvotes: 1

Lukior
Lukior

Reputation: 59

Using boost::spirit for this purpose could be a viable option. JSON is a pretty easy thing to parse with it and you will be able to fill up your array with interaction with boost::phoenix.

Upvotes: 0

Related Questions