解组json来反映结构 [英] Unmarshal json to reflected struct

查看:120
本文介绍了解组json来反映结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能将JSON解组到反向构造的结构中而不对原始类型进行硬编码?

  package main 

import(
fmt
encoding / json
reflect


类型Employee struct {
名字字符串`json:firstname`
}

func main(){
//原始结构体
orig:= new(Employee)

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

//反射结构
new:= v.Elem()。Interface()。(Employee)

//解组为反射结构
json.Unmarshal([] byte({\firstname \:\bender \}),& new)

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

在本例中,我使用了一个强制类型转换为 Employee 。但是如果我不知道这种类型呢?

当我使用 v 作为非标记时,结构将被清零。

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

当我省略演员时,我得到一张地图。这是可以理解的

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


解决方案这里的问题是,如果你在这里省略类型断言:

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

new 被推断有一个接口{} 类型。

然后当你把地址解组时,& new * interface {} (指向接口{}的指针),并且解组无法按预期工作。 p>

如果不是直接使用指针引用来获取 Elem(),那么可以避免类型断言。 p>

  func main(){
//原结构
orig:= new(Employee)

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

//反射指针
newP:= v.Inte rface()

//解组为反射结构指针
json.Unmarshal([] byte({\firstname \:\bender \}) ,newP)

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

游乐场: https://play.golang.org/ p / lTBU-1PqM4

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

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

解决方案

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\n", newP)
}

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

这篇关于解组json来反映结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆