JSON string to struct

According to the answer Reading a JSON file into ROOT C++
the code bellow works in the interpreter mode and not if I compile it.

$ root -b -q -l testjson.cxx
key: testkey value: testvalue
$ root -b -q -l testjson.cxx+
key: testkey value: testvalue
$ g++ -DMAIN  -I`root-config --incdir` testjson.cxx  `root-config --libs` -o testjson
$ ./testjson
NULL returned

ROOT version v6-22-06

What am I doing wrong?
Cheers, Rok

#include <stdlib.h>
#include <iostream>
#include <TBufferJSON.h>

struct Example {
  std::string key;
  std::string value;
Example e;

void testjson(){
  TString json="{\"_typename\" : \"Example\",\"key\" : \"testkey\",\"value\" : \"testvalue\"}";
  auto res = TBufferJSON::FromJSON<Example>(json.Data());
  if (!res)  std::cout << "NULL returned" << std::endl;
  else std::cout << "key: " << res->key << " value: "<< res->value << std::endl;
#ifdef MAIN
int main(){testjson();}

Hello @f9daq,

AFAIK, the TBufferJSON::FromJSON() function relies on TClass::GetClass() to get the layout information of struct Example. This, in turn, requires access to reflection provided by the interpreter.

Therefore, in the compiled version of your program, the TClass::GetClass() function returns NULL.


Yes, when producing compiled version, one also have to provide dictionary for the custom classes used in the I/0. The most easy way for that - use cmake as described here

Thanks, it works now.
Cheers, Rok

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.