Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ints in a protobuf struct?

I have noticed that when converting a Python dictionary to a google.protobuf.Struct the integers are turned into floats, i.e. this:

my_dict = {'id': 42}

becomes this:

fields {
    key: "id"
    value {
        number_value: 42.0
    }
}

This is very unfortunate, but looking at the proto definition of struct it seems that this is by design as there is indeed only a double number value.

Does anyone know the reason for this, and is there way around this without manually keeping track of which numbers are ints and which are floats?

like image 341
gmolau Avatar asked Aug 13 '18 08:08

gmolau


People also ask

How do you use any in Protobuf?

To use the Any type, you must import the google/protobuf/any. proto definition. In the C# code, the Any class provides methods for setting the field, extracting the message, and checking the type. Protobuf's internal reflection code uses the Descriptor static field on each generated type to resolve Any field types.

What is a Protobuf struct?

Struct. `Struct` represents a structured data value, consisting of fields which map to dynamically typed values. In some languages, `Struct` might be supported by a native representation.


1 Answers

As com.google.protobuf.Struct is create to store JSON data, it follows JSON specification which does not differentiate between Integer and Float:

https://www.rfc-editor.org/rfc/rfc7159#page-6

There are implementation of JSON that provide Integer data type such as JSONObject. However, such implementation often rely on casting numeric to Integer. See JsonNumber.isIntegral.

like image 109
marcoseu Avatar answered Oct 10 '22 15:10

marcoseu