yosh-matsuda / cpp-yyjson

Ultra-fast and intuitive C++ JSON reader/writer with yyjson backend
MIT License
63 stars 6 forks source link

Example usage #18

Closed alex-tee closed 5 months ago

alex-tee commented 5 months ago

Thanks for this library! It looks promising, but I have no idea how to use it and I can't find proper examples to do what I was able to do with C yyjson (I am trying to port my code from the C yyjson API).

How would I do this with cpp-yjson?

struct Position
{
  double ticks = 0.0;
  long frames = 0;
}

void
position_deserialize_from_json (
  yyjson_doc * doc,
  yyjson_val * pos_obj,
  Position *   pos)
{
  yyjson_obj_iter it = yyjson_obj_iter_with (pos_obj);
  pos->ticks = yyjson_get_real (yyjson_obj_iter_get (&it, "ticks"));
  pos->frames = yyjson_get_int (yyjson_obj_iter_get (&it, "frames"));
}

void
position_serialize_to_json (
  yyjson_mut_doc * doc,
  yyjson_mut_val * pos_obj,
  const Position * pos)
{
  yyjson_mut_obj_add_real (doc, pos_obj, "ticks", pos->ticks);
  yyjson_mut_obj_add_int (doc, pos_obj, "frames", pos->frames);
}

void serialize()
{
  yyjson_mut_doc * doc = yyjson_mut_doc_new (NULL);
  yyjson_mut_val * root = yyjson_mut_obj (doc);
  yyjson_mut_doc_set_root (doc, root);
  yyjson_mut_obj_add_str (doc, root, "title", "something");
  yyjson_mut_val * position_obj = yyjson_mut_obj_add_obj (doc, root, "position");
  Position my_position = { 0.1, 1 };
  position_serialize_to_json (doc, position_obj, &my_position);
  // yyjson_mut_write, yyjson_mut_doc_free, etc.
}

void deserialize(const char * json)
{
  yyjson_doc * doc = yyjson_read_opts ((char *) json, strlen (json), 0, NULL, NULL);
  yyjson_val * root = yyjson_doc_get_root (doc);
  yyjson_obj_iter it = yyjson_obj_iter_with (root);
  Position my_position = {};
  position_deserialize_from_json (doc, yyjson_obj_iter_get (&it, "position"), &my_position);
  // yyjson_doc_free, etc.
}