chrusty / protoc-gen-jsonschema

Protobuf to JSON-Schema compiler
Apache License 2.0
496 stars 101 forks source link

Wrong schema generated for google.protobuf.ListValue #143

Closed oliver closed 1 year ago

oliver commented 1 year ago

When using the google.protobuf.ListValue type from struct.proto, Protobuf will actually use an array in JSON, but the generated JSON Schema does not reflect that.

E.g. for this .proto file:

syntax = "proto2";
import "google/protobuf/struct.proto";

message SomeTestMessage {
  required int32 some_int = 1;
  required google.protobuf.ListValue some_list = 2;
}

and this C++ code:

rbc::SomeTestMessage test_msg;
test_msg.set_some_int(42);
{
  google::protobuf::Value v;
  v.set_number_value(3.1415);
  test_msg.mutable_some_list()->mutable_values()->Add(std::move(v));
}
{
  google::protobuf::Value v;
  v.set_number_value(2.7182);
  test_msg.mutable_some_list()->mutable_values()->Add(std::move(v));
}
std::string json_string;
google::protobuf::util::MessageToJsonString(test_msg, &json_string);
std::cout << "json_string: " << json_string << std::endl;

the following JSON will be written:

{
  "some_int": 42,
  "some_list": [3.1415, 2.7182]
}

But the JSON Schema generated by protoc-gen-jsonschema describes that some_list is an object with a values member. When validating the created JSON string against the generated Schema file, validation fails.

I guess this happens because Protobuf has special code for serializing these well-known types to/from JSON.

chrusty commented 1 year ago

Hello @oliver, thanks for raising this.

We aready have some specific cases for generating Google protobuf types. This probably be added without too much hassle. I'll take a look.

chrusty commented 1 year ago

Hi @oliver, I've made a PR for this: https://github.com/chrusty/protoc-gen-jsonschema/pull/145

Would you be able to try that branch out and tell me if this does what you're after?

oliver commented 1 year ago

Yes, I'll give it a try tomorrow. Thanks for the quick PR!

chrusty commented 1 year ago

Hey @oliver, I've made a new release containing the update: https://github.com/chrusty/protoc-gen-jsonschema/releases/tag/1.4.1

oliver commented 1 year ago

Great, much appreciated! Thank you for this project, it's really useful for me!