Skip to content

Example usage #18

Closed
Closed

Description

@alex-tee

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.
}

Activity

  1. Repository owner locked and limited conversation to collaborators on Jun 9, 2024
  2. converted this issue into a discussion #19 on Jun 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions