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":"[email protected]","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 關注
- 229 瀏覽
添加回答
舉報