简体   繁体   English

从结构创建 JSON,而不是结构值

[英]Creating JSON from struct, not struct value

I imagine I would need the reflect package to do this.我想我需要反射包来做到这一点。 Say I have a struct like so:假设我有一个像这样的结构:

type Inner struct {
   Whatever int
}

type ResolutionValue struct {
    Val string
    Inner
}

say I want to generate a JSON representation of the ResolutionValue struct...is there some way to create a JSON representation without instantiating it?说我想生成 ResolutionValue 结构的 JSON 表示......有没有办法在不实例化的情况下创建 JSON 表示?

Even with reflection, you would need an actual value to get the type using reflect.TypeOf .即使使用反射,您也需要一个实际值来使用reflect.TypeOf获取类型。 So I would suggest just using the zero value of your type.所以我建议只使用你的类型的零值。

json.Marshal(ResolutionValue{})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM