Skip to content

Instantly share code, notes, and snippets.

@inlinechan
Created October 19, 2017 03:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inlinechan/d12d37173f7d3f848a93eb92c6209c85 to your computer and use it in GitHub Desktop.
Save inlinechan/d12d37173f7d3f848a93eb92c6209c85 to your computer and use it in GitHub Desktop.
UnmarshalJSON from []float64 to struct(Value)
// UnmarshalJSON from []float64 to struct(Value)
package main
import (
"encoding/json"
"fmt"
)
type Value struct {
First float64
Second float64
Last float64
}
type Response struct {
Values []Value
}
func (v *Value) UnmarshalJSON(b []byte) error {
var numbers []float64
err := json.Unmarshal(b, &numbers)
if err != nil {
fmt.Printf(err.Error())
return err
}
v.First = numbers[0]
v.Second = numbers[1]
v.Last = numbers[2]
return nil
}
func main() {
data := []byte(`{"values": [[1, 2, 3], [4, 5, 6]]}`)
res := new(Response)
err := json.Unmarshal(data, &res)
if err != nil {
fmt.Printf(err.Error())
} else {
fmt.Printf("%f\n", res.Values[1].First)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment