How to represent this complex data structure using Go structures?

So, I decided to give a chance, but got stuck. Most examples of Go structures in the documentation are very simple, and I found the following JSON object designation, which I don’t know how to represent using Go structures:

{ id: 1, version: "1.0", method: "someString", params: [ { clientid: "string", nickname: "string", level: "string" }, [{ value: "string", "function": "string" }] ] } 

How would you, more experienced gophers, present some strange data in Go? And how to initialize the nested elements of the resulting structure?

+5
source share
1 answer

I would use the json.RawMessage slice for the params property .. then hide them behind the GetXXX method, which decodes it perfectly. Like that:

 type Outer struct { Id int `json:"id"` Version string `json:"version"` Method string `json:"method"` Params []json.RawMessage `json:"params"` } type Client struct { ClientId string `json:"clientid"` Nickname string `json:"nickname"` Level string `json:"level"` } .... obj := Outer{} err := json.Unmarshal([]byte(js), &obj) if err != nil { fmt.Println(err) } fmt.Println(obj.Method) // prints "someString" client := Client{} err = json.Unmarshal(obj.Params[0], &client) fmt.Println(client.Nickname) // prints "string" 

Work (quickly breaks up during lunch). Example: http://play.golang.org/p/Gp7UKj6pRK

For this, the second param will require some input from you .. but you basically look at decoding it on a fragment of any type that you created to represent it.

+12
source

Source: https://habr.com/ru/post/1207860/


All Articles