dongyi1111 2017-08-14 16:57
浏览 48
已采纳

解组json以反映结构

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
", 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 omit the cast I get a map. which is understandable

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

2条回答 默认 最新

  • dqkf49487 2017-08-14 17:43
    关注

    The problem here is that if you omit the type assertion here:

    new := v.Elem().Interface()
    

    The new is inferred to have a interface{} type.

    Then when you take the address to unmarshal, the type of &new is *interface{} (pointer to interface{}) and unmarshal does not work as you expect.

    You can avoid the type assertion if instead of getting the Elem() you work directly with the pointer reference.

    func main() {
      //Original struct
      orig := new(Employee)
    
      t := reflect.TypeOf(orig)
      v := reflect.New(t.Elem())
    
      // reflected pointer
      newP := v.Interface()
    
      // Unmarshal to reflected struct pointer
      json.Unmarshal([]byte("{\"firstname\": \"bender\"}"), newP)
    
      fmt.Printf("%+v
    ", newP)
    }
    

    Playground: https://play.golang.org/p/lTBU-1PqM4

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算