dongrunying7537 2014-01-06 01:05
浏览 35
已采纳

我如何基于类型进行json.Unmarshal

I am writing a go client for the Flowdock API. Their API for Message has a number of attributes two of which are Event and Content

When Event = message then Content is a string. When Event = comment Content is a JSON object.

I want to defer unmarhsalling Content until it is needed. To do this I map RawContent in my struct and define a Content() method on Message to return the correct object.

Here is the code to illustrate:

package main

import (
    "fmt"
    "encoding/json"
)

// Message represents a Flowdock chat message.
type Message struct {
    Event            *string          `json:"event,omitempty"`
    RawContent       *json.RawMessage `json:"content,omitempty"`
}


func (m *Message) Content() (content interface{}) {
    // when m.Event is a message the RawContent is a string
    // real code handles unmarshaling other types (removed for this example)
    return string(*m.RawContent)
}

func main() {
    var message = &Message{}
    rawJSON := `{"event": "message", "content": "Howdy-Doo @Jackie #awesome"}`
    if err := json.Unmarshal([]byte(rawJSON), &message); err != nil {
        panic(err.Error())
    }

    event := "message"
    rawMessage := json.RawMessage("Howdy-Doo @Jackie #awesome")
    want := &Message{
        Event: &event,
        RawContent: &rawMessage,
    }

    fmt.Println(message.Content(), want.Content())
}

The result of running this is: http://play.golang.org/p/eds_AA6Aay

"Howdy-Doo @Jackie #awesome" Howdy-Doo @Jackie #awesome

Note: message.Content() and want.Content() are different!

At first I did not expect the quotes to be included in message but it makes sense because of how the JSON is parsed. It is just a slice of the whole rawJSON string.

So my questions are:

  1. Should I just strip off the quotes?
  2. If so what is the simplest way in Go to strip? maybe this: http://play.golang.org/p/kn8XKOqF0z lines(6, 19)?
  3. Is this even the right approach to handling JSON that can have different types for the same attribute?

Here is a more complete example showing how I handle a JSON RawContent: http://play.golang.org/p/vrBJ5RYcql

  • 写回答

1条回答 默认 最新

  • douxu5845 2014-01-06 07:03
    关注

    Question 1:

    No, you should json.Unmarshal the content also when it only contains a string. Apart from the quotes, JSON strings may also contain backslash-escaped control characters.

    Question 2:

    Because of the answer in Question 1, do the following for the "message" case:

    var s string        
    if err := json.Unmarshal([]byte(*m.RawContent), &s); err != nil {
        panic(err)
    }
    return s
    

    Question 3:

    It is a good approach to Unmarshal the event type string and use RawMessage to store the rest of the JSON until you've evaluated the type and know what kind of structure the content has.

    You might want to consider also having a specific type also for just simple string contents, eg.:

    type MessageContent string
    

    This way you are free to implement methods on the type, allowing the Content method to return some other interface than just the empty interface{}.

    Note:

    Beware that, if you also json.Unmarshal the message string as I suggested, your Playground example will panic when trying to Unmarshal your non-quoted want.RawContent string, because it is not valid JSON.

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

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集