戈兰超范围界面{}

时间:2017-12-15 13:22:23

标签: go

我正在尝试开发简单的聊天应用程序。用户谈话来自像这样的json的webservice。我将这个json解组为map [string] interface {}。我的问题是我想要所有的" talk_messages"在for循环中。但我不能。

{
"talk_id": 0,
"receiver_id": 1,
"receiver_name":"Jack",
"sender_id": 0,
"talk_messages":[
    {
        "message_id": 0,
        "body": "Helooo",
        "send_date": "12/3/2017 4:57:15 PM",
        "sender_id": 0,
        "talk_id": 0
    },
    {
        "message_id": 1,
        "body": "Helooo",
        "send_date": "12/3/2017 4:58:15 PM",
        "sender_id": 1,
        "talk_id": 0
    },
    {
        "message_id": 2,
        "body": "Whatsapp",
        "send_date": "12/3/2017 4:59:22 PM",
        "sender_id": 0,
        "talk_id": 0
    },
    {
        "message_id": 3,
        "body": "Lorem impus",
        "send_date": "12/3/2017 5:01:15 PM",
        "sender_id": 1,
        "talk_id": 0
    }
]
}

这是我的for循环。我的问题是什么?

var talkData map[string]interface{}

if unMarshalError := json.Unmarshal([]byte(data), &talkData); unMarshalError != nil {
    fmt.Println("Talk initialize error :", unMarshalError)
}

idString := fmt.Sprintf("%v", talkData["talk_id"])
talk.id, _ = strconv.ParseInt(idString, 10, 64)

talk.playerOneId = fmt.Sprintf("%v", talkData["receiver_id"])
talk.playerTwoId = fmt.Sprintf("%v", talkData["sender_id"])
talk.receiverName = fmt.Sprintf("%v", talkData["receiver_name"])

for _, val := range talkData["talk_messages"] {
    fmt.Println(val)
}
fmt.Println(talk.id, talk.playerOneId, talk.playerTwoId)

1 个答案:

答案 0 :(得分:2)

由于您要解组为通用值(map[string]interface{}),因此您需要使用type assertion将“talk_messages”键引用的值转换为泛型类型的片段({ {1}})所以可以使用“range”关键字迭代它们,例如:

[]interface{}

更好的是,既然您提前了解了数据的结构,并且假设它是一致的,那么您可以定义直接编组数据的结构类型,而不必担心messages := talkData["talk_messages"].([]interface{}) // assert a slice type --------------^^^^^^^^^^^^^^^^ for i, message := range messages { fmt.Printf("OK: message %d => %s\n", i, message) } 类型。所有:

interface{}

另外,正如评论者所说,你应该以某种方式处理错误,而不仅仅是打印它们,否则程序会做出意想不到的事情。