Question

I am using Jsoncpp to parse json-formats for c++. I do not understand how it works though; there is a lack of documentation and examples to get me started, and I was wondering if anyone could give me some quick pointers. The only examples I've found deals with files...

  1. I'm using a HTTP stack to get a json-message in a buffer. For example, a buffer contains the message {"state":"Running"}. How do I use the Json::reader to parse this? Again the only example I've found deals with reading from files

  2. How do you write values to a Json-message? For example I want to write "monkey : no" and "running : yes" to a Json-message which I can then use in my GET request.

Thanks

UPDATE:

on 1), for example, how to parse a buffer containing a json-message like this:

char* buff;
uint32_t buff_size;
Was it helpful?

Solution

Maybe this is good sample for first part of your question:

Json::Value values;
Json::Reader reader;
reader.parse(input, values);

Json::Value s = values.get("state","default value");

OTHER TIPS

There is anything but lack of documentation. Yes, it's mainly reference documentation, but it's quite good and well cross-linked.

  1. Just read the documentation
  2. Just use this class or possibly use the other class

Sample code for your reference, below:

file.json

{
"B":"b_val2",
"A":{
        "AA":"aa_val1", 
        "AAA" : "aaa_val2",
        "AAAA" : "aaaa_val3"
     },
"C":"c_val3",
"D":"d_val4"
}

jsoncpp usage scenario as below, for above sample json file.

#include <iostream>
#include "json/json.h"
#include <fstream>

using namespace std;

int main(){

Json::Value root;
Json::Reader reader;
const Json::Value defValue;         //used for default reference
std::ifstream ifile("file.json");

bool isJsonOK = ( ifile != NULL && reader.parse(ifile, root) );
if(isJsonOK){

    const Json::Value s = root.get("A",defValue);
    if(s.isObject()){

        Json::Value s2 = s.get("AAA","");
        cout << "s2 : " << s2.asString() << endl;
    }else{
        cout << "value for key \"A\" is not object type !" << endl;
    }
}
else
    cout << "json not OK !!" << endl;

return 1;

}

Output::

s2 : aaa_val2

Additionally, I have used the "amalgamate.py" for generating and using the jsoncpp for the sample source above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top