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 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化