druybew06513 2015-09-06 16:39
浏览 7

如何解组/存储未知的json字段?

I need to Unmarshal json from a 3rd party API. Although I know the response type I need to make sure I don't loose any field that the API may introduce (the api has no documentation) so I'm wondering how can I do that. Ideally I would like to store the unknown fields in an interface{} value and perhaps encode it for later audit. Here is what i've tried so far but it doesn't work(Data field which is "unknown" at compile time is lost during unmarshalling).

Play

package main

import (
    "encoding/json"
    "fmt"
)

type Tweet struct {
    User_id int
    Message string
    Unknown
}
type Unknown map[interface{}]interface{}

func main() {
    // Define an empty interface
    var t Tweet

    // Convert JSON string into bytes
    b := []byte(`{"user_id": 1, "message": "Hello world", "Date": "somerandom date"}`)

    // Decode bytes b into interface i
    json.Unmarshal(b, &t)
    fmt.Println(t)
}
  • 写回答

1条回答 默认 最新

  • drtwqc3744 2015-09-06 19:09
    关注

    You could use RawMessage as inf suggested. Here's an example using sharktanklabs j2n package.

    package main
    
    import (
        "encoding/json"
        "fmt"
    
        "github.com/sharktanklabs/j2n"
    )
    
    type TweetData struct {
        User_id  int
        Message  string
        Overflow map[string]*json.RawMessage `json:"-"`
    }
    
    type Tweet struct {
        TweetData
    }
    
    func (c *Tweet) UnmarshalJSON(data []byte) error {
        return j2n.UnmarshalJSON(data, &c.TweetData)
    }
    
    func (c Tweet) MarshalJSON() ([]byte, error) {
        return j2n.MarshalJSON(c.TweetData)
    }
    
    func main() {
        // Define an empty interface
        var t Tweet
    
        // Convert JSON string into bytes
        b := []byte(`{"user_id": 1, "message": "Hello world", "Date": "somerandom date"}`)
    
        // Decode bytes b into interface i
        json.Unmarshal(b, &t)
        fmt.Printf("%#v
    ", t)
    }
    // Formatted output: 
    //     main.Tweet{TweetData:main.TweetData{
    //         User_id:1, 
    //         Message:"Hello world",     
    //         Overflow:map[string]*json.RawMessage{
    //             "user_id":(*json.RawMessage)(0xc82000e340), 
    //             "message":(*json.RawMessage)(0xc82000e3c0), 
    //             "Date":(*json.RawMessage)(0xc82000e440)}}}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?