簡體   English   中英

在Golang中解組json

[英]Unmarshalling json in golang

golang初學者在這里。

我想解組此處顯示的一些JSON:

 {
  "intro": {
    "title": "The Little Blue Gopher",
    "story": [
      "Once upon a time, long long ago, there was a little blue gopher. Our little blue friend wanted to go on an adventure, but he wasn't sure where to go. Will you go on an adventure with him?",
      "One of his friends once recommended going to New York to make friends at this mysterious thing called \"GothamGo\". It is supposed to be a big event with free swag and if there is one thing gophers love it is free trinkets. Unfortunately, the gopher once heard a campfire story about some bad fellas named the Sticky Bandits who also live in New York. In the stories these guys would rob toy stores and terrorize young boys, and it sounded pretty scary.",
      "On the other hand, he has always heard great things about Denver. Great ski slopes, a bad hockey team with cheap tickets, and he even heard they have a conference exclusively for gophers like himself. Maybe Denver would be a safer place to visit."
    ],
    "options": [
      {
        "text": "That story about the Sticky Bandits isn't real, it is from Home Alone 2! Let's head to New York.",
        "arc": "new-york"
      },
      {
        "text": "Gee, those bandits sound pretty real to me. Let's play it safe and try our luck in Denver.",
        "arc": "denver"
      }
    ]
  },...}

進入map [string] Context。

以下是相關定義:

type Context struct {
    title   string
    story   string 
    options *[]Option
}

type Option struct {
    text string
    arc  string
}

取消編組運行沒有錯誤,但是我得到了帶有Context結構的map [intro],該結構將所有內容初始化為nils或空字符串。

正確的做法是什么? 對於特定的用例,文檔和示例確實很難解析。

編輯:還有一個可能重復的問題,但是這個問題有點不同,因為它需要引入字符串標簽才能正確工作。

為了進行編組和解組,必須導出字段。

    type Context struct {
        Title   string   `json:"title"`
        Story   string   `json:"story"`
        Options []Option `json:"options"`
    }

    type Option struct {
        Text string `json:"text`
        Arc  string `json:"arc"`
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM