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 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入