Created
October 19, 2017 03:04
-
-
Save inlinechan/d12d37173f7d3f848a93eb92c6209c85 to your computer and use it in GitHub Desktop.
UnmarshalJSON from []float64 to struct(Value)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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