如何在Go中自定义JSON编码输出?

Men*_*eng 5 json go

我想自定义结构的编码格式但得到错误:json:错误调用MarshalJSON类型为main.Info:文字中的无效字符'o'为false(期待'a')我的代码出了什么问题?

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "log"
)

type Info struct {
    name string
    flag bool
}

func (i Info) MarshalJSON() ([]byte, error) {
    var b bytes.Buffer
    b.Write([]byte(i.name))
    if i.flag {
        b.Write([]byte(`"true"`))
    } else {
        b.Write([]byte(`"false"`))
    }   
    return b.Bytes(), nil 
}

func main() {
    a := []Info{
        {"foo", true},
        {"bar", false},
    }   
    out, err := json.Marshal(a)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf(string(out))
}
Run Code Online (Sandbox Code Playgroud)

Bet*_*mos 0

将您自己的字符串写入缓冲区就消除了json.Marshal(). 也许是这样的:

type Info struct {
    Name string `json:"name"` // Struct fields should have capital first letter
                              // if you want it to be found by the marshaller.
    Flag bool `json:"flag"`   // json:"flag" assigns the object key in json format
}
Run Code Online (Sandbox Code Playgroud)

然后是这样的:

myInfo := Info {
    Name: "Foo",
    Flag: true,
}
slc, _ := json.Marshal(myInfo)
fmt.Println(string(slc))
Run Code Online (Sandbox Code Playgroud)