JohnGB JohnGB - 1 year ago 83
JSON Question

How best to send complex data with FCM / GCM using Go

Both the FCM and GCM documentation give the structure of the

payload as a map[string]string (although google's GCM package implements it at a map[string]interface{})

However, there are many cases where a simple flat key:value structure doesn't meet the needs of an application. Some examples are when a slice of values is needed, or when another non-trivial struct needs to be sent.

What would be the cleanest way of sending more complicated data structures as a map[string]string?

Conclusion: I have marked the answer by fl0cke as correct given that it provides a solution to sending complex data with FCM / GCM using Go. However, it is clear from the FCM documentation, that the intention is for the data to be key:value string pairs moving forward, and so to be sure that nothing gets broken in the future, I will be sticking to simple key:value string pairs.

Answer Source

According to this answer, it is possible to send nested data. To do that, you can write your own FCM Client or fork google's implementation and change the type definition of Data from

type Data map[string]interface{}


type Data interface{}

Then you can send any type that is JSON serializable (e.g. nested structs).

It is also possible to send the data as a JSON string without changing the type definition of Data:

// first marshal your complex data structure
complexData := someComplexStruct{...}
b, _ := json.Marshal(complexData)

// then assign the returned json string to one key of your choice
data := map[string]interface{}{"key":string(b)}

You probably have to unquote the string before parsing it on the client.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download