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 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题