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

Working with google.protobuf.Any in newest version #764

Open
manni83 opened this issue Apr 19, 2017 · 3 comments
Open

Working with google.protobuf.Any in newest version #764

manni83 opened this issue Apr 19, 2017 · 3 comments

Comments

@manni83
Copy link

manni83 commented Apr 19, 2017

In #677 a wrapper for google.protobuf.Any was added. I wanted to use this because it would be very convenient when working with protobuf.Any, but it did not work. Here is an example based on the unit test comp_google_protobuf_any.js what I would like to do:

    foo = Foo.fromObject({
        foo: {
            "@type": ".Bar",
            bar: "a"
        }
    });

    test.ok(foo.foo instanceof Bar.ctor, "should unwrap wrapped Bar in fromObject");
  
    // Encode and decode again -> foo.foo is not serialized!
    var foo2 = Foo.decode(Foo.encode(foo).finish());
    obj = foo2.toObject(foo2, { json: true });

    // This fails
    test.same(obj.foo, { "@type": ".Bar", bar: "a" }, "this does not work at the moment");

Or is there any other way how I can initialize a message that contains a google.protobuf.Any easily?

@jianfenkezhan
Copy link

can anyone provide an example?

@koliyo
Copy link

koliyo commented Feb 10, 2019

This works for me, but would be really nice if this was wrapped in some generated helper method

protocolbuffers/protobuf#2612 (comment)

Eg, in the python library this is much more automatic, as well as in the golang library.

@xyy94813
Copy link

xyy94813 commented Aug 5, 2021

const protobufjs = require('protobufjs');
const path = require('path');

const protoFilePath = path.resolve(__dirname, './my.proto')

protobufjs.load(protoFilePath, function (
  err,
  root,
) {
  if (err) {
    console.error(err);
    throw err;
  }
  const MyMessage = root.lookupType(
    'MyMessage',
  );
  const MyData = root.lookupType(
    'MyData',
  );
  const GoogleAny = root.lookupType('Any');
  
  const myMsg = MyMessage.fromObject({
    data: GoogleAny.toObject(
      MyData.fromObject({ 
        // ...
      })
    )
  })
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants