doulan6150 2015-05-12 16:00
浏览 65
已采纳

将类型编码为JSON时将字符串追加到成员

I have this type with a value member called "Url". When encoding this type to json, I want to prepend the HOST value in front of the Url. What is the best way to achieve that?

In this example, the Println statement prints {"url":"/thisurl"}, I want it to print {"url":"http://myhost.com/thisurl"}

package main

import "fmt"
import "encoding/json"

type Post struct {
  Url string `json:"url"`
}

const (
  HOST = "http://myhost.com"
)

func main() {
  post := Post{"/thisurl"}
  marshaled, _ := json.Marshal(post)

  fmt.Println(string(marshaled))
   //{"url":"/thisurl"}
}

Update

I could re-assign post.Url right before the json.Marshal line

post.Url = fmt.Sprintf("%s%s", HOST, post.Url)

But that feels a little messy, if I have to remember to do a reassignment every time I want to encode to json.

I don't want to change the value of post.Url, I simply want to change how it is represented as json.

  • 写回答

1条回答 默认 最新

  • duanhuang4306 2015-05-12 16:35
    关注

    If you want to change the (un)marshalling behaviour then use a custom type that implements json.Marshaler (and possibly json.Unmarshaler).

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Post struct {
        URL URLString `json:"url"`
    }
    
    const (
        Host = "http://myhost.com"
    )
    
    type URLString string
    
    func (u URLString) MarshalJSON() ([]byte, error) {
        return []byte(fmt.Sprintf(`"%s%s"`, Host, u)), nil
    }
    
    func main() {
        post := Post{"/thisurl"}
        marshaled, _ := json.Marshal(post)
    
        fmt.Println(string(marshaled))
        //{"url":"http://myhost.com/thisurl"}
    }
    

    <kbd>Playground</kbd>

    (also note, using all caps for constants is not idiomatic, and golint recommends URL, MyURL, HTTP, ID vs Url, MyUrl, or Id).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题