Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JsonCodec should probably automatically initialize itself #1064

Open
zenhack opened this issue Sep 17, 2020 · 3 comments
Open

JsonCodec should probably automatically initialize itself #1064

zenhack opened this issue Sep 17, 2020 · 3 comments

Comments

@zenhack
Copy link
Contributor

zenhack commented Sep 17, 2020

# testcase.capnp
@0x8d8eb9e37e9bbfd9;

using Json = import "/capnp/compat/json.capnp";

struct Foo {
  barBaz @0 :Void $Json.name("bar_baz");
}
// testcase.c++
#include "testcase.capnp.h"
#include <capnp/serialize.h>
#include <capnp/compat/json.h>
#include <iostream>

int main() {
  capnp::MallocMessageBuilder msg;

  auto foo = msg.initRoot<Foo>();
  auto jsonStr = capnp::JsonCodec().encode(foo);
  std::cout << jsonStr.cStr() << std::endl;
  return 0;
}
# build.sh
set -ex
capnp compile -oc++ *.capnp
c++ -o testcase *.c++ -lkj -lcapnp -lcapnp-json

Output:

{"barBaz":null}

...but iiuc the field should be rendered as "bar_baz".

@bretthoerner
Copy link
Contributor

I think you just need to call handleByAnnotation<Foo>(); on your JsonCodec first:

void handleByAnnotation(Schema schema);
template <typename T> void handleByAnnotation();
// Inspects the given type (as specified by type parameter or dynamic schema) and all its
// dependencies looking for JSON annotations (see json.capnp), building and registering Handlers
// based on these annotations.
//
// If you'd like to use annotations to control JSON, you must call these functions before you
// start using the codec. They are not loaded "on demand" because that would require mutex
// locking.

@zenhack
Copy link
Contributor Author

zenhack commented Sep 17, 2020

Aha! thanks, closing.

@zenhack zenhack closed this as completed Sep 17, 2020
@kentonv
Copy link
Member

kentonv commented Sep 18, 2020

Yeah this has proven to be a source of confusion. :/

Since JsonCodec is designed to be callable from multiple threads, we either need an explicit initialization method, or we need to use thread-safe lazy init, and thread-safe lazy init just feels so hacky, but maybe it's the right thing to do after all.

@kentonv kentonv reopened this Sep 18, 2020
@kentonv kentonv changed the title json codec appears to ignore Json.name annotations on fields? JsonCodec should probably automatically initialize itself Sep 18, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants