【问题标题】:Go: Marshal empty struct into jsonGo:将空结构编组为 json
【发布时间】:2014-10-05 09:42:18
【问题描述】:

我正在尝试将结构编组为 json。它在结构具有值时起作用。但是,当结构没有价值时,我无法访问网页:

去:

type Fruits struct {
    Apple []*Description 'json:"apple, omitempty"'
}

type Description struct {
    Color string
    Weight int
}

func Handler(w http.ResponseWriter, r *http.Request) {
    j := {[]}
    js, _ := json.Marshal(j)
    w.Write(js)
}

错误是因为 json.Marshal 无法编组空结构吗?

【问题讨论】:

  • 什么错误?你明确地忽略了这个错误。检查它可能会有所帮助。此外,{[]} 在​​ Go 中是无效语法。

标签: go


【解决方案1】:

请看这里:http://play.golang.org/p/k6d6y7TnIQ

package main

import "fmt"
import "encoding/json"

type Fruits struct {
    Apple []*Description `json:"apple, omitempty"`
}

type Description struct {
    Color string
    Weight int
}

func main() {
    j := Fruits{[]*Description{}} // This is the syntax for creating an empty Fruits
    // OR: var j Fruits
    js, err := json.Marshal(j)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(js))
}

【讨论】:

    猜你喜欢
    • 2013-08-07
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2020-01-12
    相关资源
    最近更新 更多