Advertisement
Guest User

Untitled

a guest
Jun 4th, 2015
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.07 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "encoding/json"
  5.     "fmt"
  6.     ms "github.com/mitchellh/mapstructure"
  7. )
  8.  
  9. type s1 struct {
  10.     Type  string `"json:type"`
  11.     Value int    `"json:value"`
  12. }
  13.  
  14. type s2 struct {
  15.     Type  string `"json:type"`
  16.     Value string `"json:value"`
  17. }
  18.  
  19. func main() {
  20.     raw := []byte(`[{"type": "number", "value": 15}, {"type": "string", "value": "Hello!"}]`)
  21.  
  22.     var input []map[string]interface{}
  23.     if err := json.Unmarshal(raw, &input); err != nil {
  24.         fmt.Println(err)
  25.         return
  26.     }
  27.  
  28.     fmt.Println(input)
  29.  
  30.     for _, r := range input {
  31.         switch t := r["type"]; t {
  32.         case "number":
  33.             var v1 s1
  34.             config := &ms.DecoderConfig{TagName: "json", Result: &v1}
  35.             decoder, _ := ms.NewDecoder(config)
  36.             decoder.Decode(r)
  37.             fmt.Printf("%+v\n", v1)
  38.         case "string":
  39.             var v2 s2
  40.             config := &ms.DecoderConfig{TagName: "json", Result: &v2}
  41.             decoder, _ := ms.NewDecoder(config)
  42.             decoder.Decode(r)
  43.             fmt.Printf("%+v\n", v2)
  44.         }
  45.     }
  46. }
  47. // Output:
  48. // [map[type:number value:15] map[value:Hello! type:string]]
  49. // {Type:number Value:15}
  50. // {Type:string Value:Hello!}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement