doswy02440 2019-04-19 13:11
浏览 37

如何解组此json字符串

I'm having some problem reading this type of json.

["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}]

i try with many libraries.

type SEND struct {
    Mgs string `json:"Msg"`
    //SEND MSG
}

type MSG struct {
    CMD  string `json:"cmd"`
    ID   string `json:"id"`
    ACK  int    `json:"ack"`
    FROM string `json:"from"`
    TO   string `json:"to"`
    T    int64  `json:"t"`
}

func main() {
    data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}] `
    var dd SEND
    err := json.Valid([]byte(data))
    fmt.Println("Is valid XML?->", err)
    json.Unmarshal([]byte(data), &dd)
    fmt.Println("1", dd)
    fmt.Println("2", dd.Mgs)

}

Al always a receive empty and the json it's valid

Is valid XML?-> true
1 {}
2 EMPTY
  • 写回答

1条回答 默认 最新

  • doudi8525 2019-04-19 13:27
    关注

    In this case you have array with string and object in your json, so you have to use interface{} on golang side, must be something like:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        data := `["Msg",{"cmd":"ack","id":"B81DA375B6C4AA49D262","ack":2,"from":"18094158994@c.us","to":"18099897215@c.us","t":1555446115}] `
        var d []interface{}
        err := json.Unmarshal([]byte(data), &d)
        fmt.Printf("err: %v 
    ", err)
        fmt.Printf("d: %#v 
    ", d[0])
        fmt.Printf("d: %#v 
    ", d[1])
    }
    

    Result will look like:

    err: <nil>
    d: "Msg"
    d: map[string]interface {}{"id":"B81DA375B6C4AA49D262", "ack":2, "from":"18094158994@c.us", "to":"18099897215@c.us", "t":1.555446115e+09, "cmd":"ack"}
    

    So 1st element in slice d is string Msg,
    and 2nd element in slice is map map[string]interface {} and now you can do something else with this map.

    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算