如何编组忽略struct选项? [英] How to marshal ignoring the struct options?

查看:50
本文介绍了如何编组忽略struct选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此类似的结构:

I have a struct similar to this:

type MyStruct struct {
    Type                   int     `json:"operatortypeid,string"`
    Cost                   float32 `json:"cost,string"`
    CostPerTransaction     float32 `json:"cost_per_transaction,string"`
}

我正在使用 string 选项,因为我在json请求中收到的数据总是被引用,但是我想添加一些类型安全性来处理并将其发送到数据库.

I'm using the string option because the data I receive in the json request is always quoted, but I want to add some type safety in order to process and send it to the data base.

在解组时,数据类型正确,但是当我将其编组回json时,将应用结构选项 string ,将其全部引用.

On Unmarshalling, the data types are correct, but when I marshall back into json it applies the struct option string, which makes it all quoted.

是否可以封送该结构,并使其忽略该结构选项?

Is there any way to marshall the struct and have it ignore the struct options?

推荐答案

不完全是,但是由于struct标记只是元数据,因此它们不会影响转换;因此您可以执行以下操作:

Not exactly, but because struct tags are only metadata, they don't affect conversion; so you can do something like:

type MyStructIn struct {
    Type                   int     `json:"operatortypeid,string"`
    Cost                   float32 `json:"cost,string"`
    CostPerTransaction     float32 `json:"cost_per_transaction,string"`
}

type MyStructOut struct {
    Type                   int     
    Cost                   float32 
    CostPerTransaction     float32 
}

in := MyStructIn{}
json.Unmarshal(input, &in)
out := MyStructOut(in)
output,_ := json.Marshal(&out)

这篇关于如何编组忽略struct选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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