mercredi 20 septembre 2017

Unpack generic protobuf.Any message

Consider the following .proto structure:

syntax = "proto3";    
import "any.proto";

message TranslatableText {
    message ExampleText1 {
        string param1 = 1;
        int32 param2 = 2;
        float param3 = 3;
    }

    message ExampleText2 {
        string param1 = 1;
        string param2 = 2;
    }

    google.protobuf.Any text = 1;
}

What I want to do:

Our Java-Application creates a TranslataleText, where it is ensured that the Any text-member only holds one of the inner messages of TranslataleText.

This TranslataleText object is then serialized and transmitted to another application, which needs to unpack the text and convert it into a JSON with the following format:

{
    name: "ExampleText1",
    parameters: ["valueOfParam1", 22, 1.5]
}

The problem:

The problem lies in the unpack-step. Protobufs Any class offers the following method:

<T extends Message> T unpack(Class<T> clazz) 

All I need is a Message object to get the FieldDescriptors and their value for conversion into JSON. I am not interested in the actual, concrete type.

Any also has a String getTypeUrl() method which returns com.<omitted>.TranslatableText.ExampleText1

Unfortunately, I am not able to use this type url to retrieve the .class that I need for unpacking. And I don't see any API that would allow us to read the individual message fields without unpacking the message first.

Can this be done (perferably without Java reflection)?





Aucun commentaire:

Enregistrer un commentaire