dsj2014 2018-01-17 16:10
浏览 85
已采纳

JSON密钥可以是字符串或对象

I want to parse some JSON but one key is either a string or an object.

Here is my current struct: https://github.com/PhillippOhlandt/pmtoapib/blob/master/CollectionItemRequest.go#L10

type CollectionItemRequest struct {
    Url         string          `json:"url"`
    Method      string          `json:"method"`
    Header      []RequestHeader `json:"header"`
    Body        RequestBody     `json:"body"`
    Description string          `json:"description"`
}

Here the "Url" attribute can not only a string but also an object.

I started to create an own struct for it that covers the object case.

type CollectionItemRequestUrl struct {
    Raw string `json:"raw"`
}

type CollectionItemRequest struct {
    Url         CollectionItemRequestUrl `json:"url"`
    Method      string                   `json:"method"`
    Header      []RequestHeader          `json:"header"`
    Body        RequestBody              `json:"body"`
    Description string                   `json:"description"`
}

But then the string version won't work anymore. Is there a way to have both cases working and getting the value via a getter, like request.Url.Get?

EDIT:

Here are the two versions of the JSON:

    "request": {
        "url": {
            "raw": "http://localhost:8081/users?per_page=5&page=2",
            "protocol": "http",
            "host": [
                "localhost"
            ],
            "port": "8081",
            "path": [
                "users"
            ],
            "query": [
                {
                    "key": "per_page",
                    "value": "5",
                    "equals": true,
                    "description": ""
                },
                {
                    "key": "page",
                    "value": "2",
                    "equals": true,
                    "description": ""
                }
            ],
            "variable": []
        },

And

"request": {
                "url": "http://localhost:8081/users/2",

Note: Only subsets, the whole JSON would be too long.

  • 写回答

1条回答 默认 最新

  • donglu5000 2018-01-17 16:51
    关注

    Have a type that has a custom unmarshal method that will first unmarshal into an empty interface and then does a type switch on whether it got a string or a map[string]interface{} such as this:

    type example struct {
        URL myURL `json:"url"`
    }
    
    type myURL struct {
        url string
    }
    
    func (u *myURL) MarshalJSON() ([]byte, error) {
        return json.Marshal(u.url)
    }
    
    func (u *myURL) UnmarshalJSON(data []byte) error {
        var raw interface{}
        json.Unmarshal(data, &raw)
        switch raw := raw.(type) {
        case string:
            *u = myURL{raw}
        case map[string]interface{}:
            *u = myURL{raw["raw"].(string)}
        }
        return nil
    }
    
    const myStringURL string = `{"url": "http://www.example.com/as-string"}`
    const myNestedURL string = `{"url": {"raw": "http://www.example.com/as-nested"}}`
    
    func main() {
        var stringOutput example
        json.Unmarshal([]byte(myStringURL), &stringOutput)
        fmt.Println(stringOutput)
    
        var nestedOutput example
        json.Unmarshal([]byte(myNestedURL), &nestedOutput)
        fmt.Println(nestedOutput)
    }
    

    Runnable in go playground here:

    https://play.golang.org/p/I6KC4aXHpxm

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

报告相同问题?

悬赏问题

  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿