Go:将空结构体编组为 JSON

huangapple go评论70阅读模式
英文:

Go: Marshal empty struct into json

问题

我正在尝试将一个结构体转换为JSON。当结构体有值时,它可以正常工作。然而,当结构体没有值时,我无法访问网页:

Go代码:

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无法将空结构体转换为JSON吗?

英文:

I'm trying to marshal a struct into json. It works when the struct has values. However, I'm unable to access the webpage when the struct has no value:

Go:

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)
}

Is the error because json.Marshal cannot marshal an empty struct?

答案1

得分: 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{}} // 这是创建一个空的 Fruits 的语法
    // 或者:var j Fruits
    js, err := json.Marshal(j)
    if err != nil {
        fmt.Println(err)
        return
    }
    fmt.Println(string(js))
}
英文:

See here: 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))
}

huangapple
  • 本文由 发表于 2014年10月5日 09:27:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/26198744.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定