Search code examples
protocol-buffers

Convert to protobuf format


I have file with that text

 5 {
    1: "Capability"
    2 {
      1: "READ"
      2: 0
    }
    2 {
      1: "SSH"
      2: 12
    }
  }

I know that is a protobuf structure. How can I convert this data to normal protobuf file?

Protoc give me error message


Solution

  • "I know that is a protobuf structure."

    That might have come from something protobuf related, but: it must have been a tortuous journey, because no: that isn't directly protobuf anything and AFAIK nothing is going to parse that "as is" - it isn't protobuf binary and it isn't the opinionated protobuf JSON variant. It looks like the output of protoc with the --decode_raw option? Note that this is for display purposes only.

    However, let's see what we can infer, and reverse-engineer a protobuf schema; all we know about the root message is that it has another message as field 5; that thing has a string in field one, and some repeated message in field 2, with that inner-most message being a string and an integer in fields 1 and 2, so let's assume something like:

    syntax = "proto3";
    
    message MyRootMessage {
        Layer1 layer1 = 5;
    }
    message Layer1 {
        string name = 1;
        repeated Layer2 layer2 = 2;
    }
    message Layer2 {
        string name = 1;
        int32 number = 2;
    }
    

    so: you would compile that in your language of choice via protoc, and (again in your language of choice): populate it - for example:

    var root = new MyRootMessage {
        Layer1 = new {
            Name = "Capability",
            Layer2s = {
                new { Name = "READ", Number = 0 },
                new { Name = "SSH", Number = 12 },
            }
        }
    };
    

    then serialize that using your chosen language/frameworks serialize API.


    Alternatively, if you still have the binary that you used with protoc --decode_raw, once you have reverse-engineered a schema by inspection (as above), you can construct a wrapper to deserialize your binary, using the normal code-gen options.