dry0106 2018-01-23 12:55
浏览 38
已采纳

如何在Golang中将结构解编为Map [关闭]

I have a Json:

{
  "id": "me",
  "name": "myname",
  "planets": {
      "EARTH": 3,
      "MARS": 4
  }
}

I don't know how to unmarshal planets field into map[string]int, so I'll get access to the elements without unmarshaling them too like in this example: json to map Golang

Here is the code:

package main

import (
   "encoding/json"
   "fmt"
  )

type User struct {
   ID      string `json:"id"`
   Name    string `json:"name"`
   Planets struct {
       Planet map[string]*json.RawMessage
    } `json:"planets"`
}

 func main() {
    data := `{
      "id": "me",
      "name": "myname",
      "planets": {
      "EARTH": 3,
       "MARS": 4
      }
    }`

   user := &User{}
   err := json.Unmarshal([]byte(data), user)
   if err != nil {
       fmt.Println("ERROR " + err.Error())
   }
    fmt.Println(user.ID)
    fmt.Println(user.Planets.Planet["EARTH"])
  }

fmt.Println(user.Planets.Planet["EARTH"]) - returns

fmt.Println(user.Planets["EARTH"]) - does not support indexing

  • 写回答

1条回答 默认 最新

  • dsl36367 2018-01-23 13:30
    关注

    Here is an example with marshal and unmarshal using your object definition

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type MyObject struct {
        ID      string         `json:"id"`
        Name    string         `json:"name"`
        Planets map[string]int `json:"planets"`
    }
    
    func main() {
        aa := &MyObject{
            ID:   "123",
            Name: "pepe",
            Planets: map[string]int{
                "EARTH": 3,
                "MARS":  4,
            },
        }
        // Marshal
        out, err := json.Marshal(aa)
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(string(out))
    
        // Unmarshal
        bb := &MyObject{}
        err = json.Unmarshal(out, bb)
        fmt.Println(bb.ID, bb.Name, bb.Planets)
    
    }
    

    and you can get an element of the map with bb.Planets["EARTH"]

    I hope you can find this useful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥20 求用stm32f103c6t6在lcd1206上显示Door is open和password:
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法