【问题标题】:How to marshal ignoring the struct options?如何编组忽略结构选项?
【发布时间】:2021-01-20 19:35:52
【问题描述】:

我有一个类似这样的结构:

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

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

在解组时,数据类型是正确的,但是当我编组回 json 时,它应用了结构选项 string,这使得它全部被引用。

有没有办法编组结构并让它忽略结构选项?

【问题讨论】:

    标签: json go


    【解决方案1】:

    不完全是,但由于结构标签只是元数据,它们不会影响转换;所以你可以这样做:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多