gmolau
gmolau

Reputation: 3005

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?

Upvotes: 13

Views: 5022

Answers (1)

marcoseu
marcoseu

Reputation: 3952

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.

Upvotes: 1

Related Questions