dvidelabs / flatcc

FlatBuffers Compiler and Library in C for C
Apache License 2.0
632 stars 180 forks source link

Example of using json_printer on a sub-tree of schema #200

Closed Dweller closed 2 years ago

Dweller commented 2 years ago

I've no issue in printing the entire Schema tree form the root what I'm looking for is an example of printing partial sub-trees.

e.g. Given the schema

Table Dependant {
   name: string;
   age: int;
}

table Guardian {
   name : string;
   age : int;
   Dependant [ Dependant ]
}

root_type Guardian;

Lets say I receive multiple flat buffers of root type Guardian.. Is there a why I can just print loop through each of them and output all of the Dependants using the JSON printer?

Thanks in advance.

mikkelfj commented 2 years ago

Yes this is certainly possible. I have not tested this, but let me know if it doesn't work.

After you build the test cases, e.g. using scripts/test.sh, you will find test/Debug/json/test/generated/monster_test_json_printer.h, as an example.

Near the bottom of the file you will see

static inline int Fantasy_Movie_print_json_as_root(flatcc_json_printer_t *ctx, const void *buf, size_t bufsiz, const char *fid)
{
    return flatcc_json_printer_table_as_root(ctx, buf, bufsiz, fid, Fantasy_Movie_print_json_table);
}

The last argument is a pointer to the actual print function. The library function flatcc_json_printer_table_as_root in src/runtime/json_printer.c will set up a td table decriptor that points to the root table. You will need to initialize the table descriptor to point to your table instead and call you tables printer function.

https://github.com/dvidelabs/flatcc/blob/5bc7c3512109e5fd6ea231fe1d76f09e1ce7a24e/src/runtime/json_printer.c#L1283-L1292

You can almost just call print_table_object with your tables print function and table pointer, but it is a static function. Instead you should be able to copy its logic to your own code.

You might have to dig a bit into the code before you get it to work, but it should definitely be possible.

Dweller commented 2 years ago

Thanks I've got it working now.. For both the current json printer and my own xml printer.

mikkelfj commented 2 years ago

Good, thanks for the update.