/* * call-seq: * MessageClass.encode_json(msg) => json_string * * Encodes the given message object into its serialized JSON representation. */ VALUE Message_encode_json(VALUE klass, VALUE msg_rb) { VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned); Descriptor* desc = ruby_to_Descriptor(descriptor); stringsink sink; stringsink_init(&sink); { const upb_handlers* serialize_handlers = msgdef_json_serialize_handlers(desc); upb_json_printer* printer; stackenv se; VALUE ret; stackenv_init(&se, "Error occurred during encoding: %s"); printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink); putmsg(msg_rb, desc, upb_json_printer_input(printer), 0); ret = rb_str_new(sink.ptr, sink.len); stackenv_uninit(&se); stringsink_uninit(&sink); return ret; } }
/* * call-seq: * MessageClass.encode_json(msg) => json_string * * Encodes the given message object into its serialized JSON representation. */ VALUE Message_encode_json(int argc, VALUE* argv, VALUE klass) { VALUE descriptor = rb_ivar_get(klass, descriptor_instancevar_interned); Descriptor* desc = ruby_to_Descriptor(descriptor); VALUE msg_rb; VALUE preserve_proto_fieldnames = Qfalse; stringsink sink; if (argc < 1 || argc > 2) { rb_raise(rb_eArgError, "Expected 1 or 2 arguments."); } msg_rb = argv[0]; if (argc == 2) { VALUE hash_args = argv[1]; if (TYPE(hash_args) != T_HASH) { rb_raise(rb_eArgError, "Expected hash arguments."); } preserve_proto_fieldnames = rb_hash_lookup2( hash_args, ID2SYM(rb_intern("preserve_proto_fieldnames")), Qfalse); } stringsink_init(&sink); { const upb_handlers* serialize_handlers = msgdef_json_serialize_handlers(desc, RTEST(preserve_proto_fieldnames)); upb_json_printer* printer; stackenv se; VALUE ret; stackenv_init(&se, "Error occurred during encoding: %s"); printer = upb_json_printer_create(&se.env, serialize_handlers, &sink.sink); putmsg(msg_rb, desc, upb_json_printer_input(printer), 0); ret = rb_enc_str_new(sink.ptr, sink.len, rb_utf8_encoding()); stackenv_uninit(&se); stringsink_uninit(&sink); return ret; } }