duanliaoyin3171 2018-06-04 21:15
浏览 62
已采纳

封送至JSON时转换类型

My question is very similar to this one, however instead of converting a float64 to a string which is handled using the string tag. In my case I'm trying to convert a ObjectID to a string using it's .Hex() method. And, vice versa using the .FromHex() function on the way back.

However, more generically how do I convert from type X to type Y & back during the Marshal & Unmarshaling?

My Example:

package main

import (
    "log"
    "fmt"
    "encoding/json"
    "github.com/mongodb/mongo-go-driver/bson/objectid"
)

type Greeting struct {
    Id          *objectid.ObjectID  `json:"id"`
    Greeting    string              `json:"greeting,omitempty"`
}


func main() {
    // Create ObjectID
    id, err := objectid.FromHex("5b14dd20f6418c8443a5ffec")
    if err != nil { log.Fatal(err) }

    // Create Greeting
    g := Greeting{&id, "Hello, World!"}

    // Marshal to json
    j, err := json.Marshal(g)
    if err != nil { log.Fatal(err) }

    // Print Json
    fmt.Printf("Json: %s", string(j))

}

Output:

Json: {"id":[91,20,221,32,246,65,140,132,67,165,255,236],"greeting":"Hello, World!"}

Whereas, what I'd like is:

Json: {"id":"5b14dd20f6418c8443a5ffec","greeting":"Hello, World!"}
  • 写回答

2条回答 默认 最新

  • dongyuan7981 2018-06-04 21:34
    关注

    You should write your own (un)marshalling function in which you process your conversions/conditions and handle it as argument in calling the json (un)marshalling.

    type Whatever struct {
       someField int
    }
    
    func (w Whatever) MarshalJSON() ([]byte, error) {
        return json.Marshal(struct{
            SomeField int `json:"some_field"`
        }{
            SomeField: w.someField,
        })
    }
    
    func (w Whatever) MarshalJSON() ([]byte, error) {
       return json.Marshal(map[string]interface{}{
           "some_field": w.SomeField,
       })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。