3 回答
TA贡献1811条经验 获得超6个赞
试试这个: https: //play.golang.com/p/UICf_uNNFdC
为了提高代码的可读性,我发表了很多评论。确保正确处理错误并删除调试打印。
package main
import (
"encoding/json"
"log"
"strings"
)
type Presence struct {
Presence string
ID string `json:"id"`
Type string `json:"type"`
Deny bool `json:"deny"`
}
type JsonHandler struct {
Name string `json:"name"`
Dat Presence `json:"dat"`
}
func main() {
var (
// Used for unmarshal a given json
packedData []json.RawMessage
err error
// Data that does not have a related json key
name []byte
// Used for extract the raw data that will be unmarshalled into the Presence struct
temp []byte
// Nested json
jsonPresence Presence
handler JsonHandler
)
s := `["Presence",{"id":"905356870666@c.us","type":"unavailable","deny":true}]`
log.Println("Dealing with -> " + s)
// Unmarshall into a raw json message
err = json.Unmarshal([]byte(s), &packedData)
if err != nil {
panic(err)
}
// Extract the presence
log.Println("Presence: ", string(packedData[0]))
// Extract the nested json
log.Println("Packed: ", string(packedData[1]))
// NOTE: 0 refers to the first value of the JSON
name, err = packedData[0].MarshalJSON()
if err != nil {
panic(err)
}
log.Println("Value that does not have a key: " + string(name))
handler.Name = strings.Replace(string(name), "\"", "", -1)
// NOTE: 1 refers to the second value of the JSON, the entire JSON
// Unmarshal the nested Json into byte
temp, err = packedData[1].MarshalJSON()
if err != nil {
panic(err)
}
// Unmarshal the raw byte into the struct
err = json.Unmarshal(temp, &jsonPresence)
if err != nil {
panic(err)
}
log.Println("ID:", jsonPresence.ID)
log.Println("Type:", jsonPresence.Type)
log.Println("Deny:", jsonPresence.Deny)
handler.Dat = jsonPresence
log.Println("Data unmarshalled: ", handler)
}
TA贡献1817条经验 获得超14个赞
去游乐场链接: https: //play.golang.org/p/qe0jyFVNTH1
这里存在几个问题:
1. Json 包不能引用未导出的结构元素。因此请在以下代码段中使用 Deny 而不是拒绝。这适用于结构内声明的所有变量
2. json 字段标记不正确. 例如。mapstructure:"id"应该是json:"id"
3。要解析的json包含两个不同的元素,即字符串“Presence”和嵌套的json对象。它不能被解析为单个元素。最好声明“Presence”为key,嵌套json为价值。
4.拒绝变量应该是bool而不是string
TA贡献1834条经验 获得超8个赞
哇,通过仅添加这些代码解决了问题
这里去朗链接: https: //play.golang.org/p/doHNWK58Cae
func (n *JsonHandler) UnmarshalJSON(buf []byte) error {
tmp := []interface{}{&n.Name, &n.Dat}
wantLen := len(tmp)
if err := json.Unmarshal(buf, &tmp); err != nil {
return err
}
if g, e := len(tmp), wantLen; g != e {
return fmt.Errorf("wrong number of fields in Notification: %d != %d", g, e)
}
return nil
}
- 3 回答
- 0 关注
- 338 浏览
添加回答
举报
