lundi 14 août 2017

Unmarshal json to reflected struct

Is it possible to unmarshal json into a struct made from reflection without hardcoding the original type?

package main

import (
  "fmt"
  "encoding/json"
  "reflect"
)

type Employee struct {
  Firstname string     `json:"firstname"`
}

func main() {
  //Original struct
  orig := new(Employee)

  t := reflect.TypeOf(orig)
  v := reflect.New(t.Elem())

  //Reflected struct
  new := v.Elem().Interface().(Employee)

  // Unmarshal to reflected struct
  json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), &new)

  fmt.Printf("%+v\n", new)
}

I used a cast to Employee in this example. But what if i don't know the type?

When i just use v for the unmarhaling the struct will be zeroed.

json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v)

When i ommit the cast i get a map. which is understandable

json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), v.Elem().Interface())





Aucun commentaire:

Enregistrer un commentaire