英文:
go json decoder definition , what should be as input in this case
问题
我有一个用于将结构体编码为JSON对象的Go代码。
有人可以告诉我如何解码它吗?
我不明白的是,要定义解码器,输入应该是什么?
包 main
import "encoding/json"
import "bytes"
//import "os"
import "fmt"
func main() {
var emptyAppendEntriesResponse bytes.Buffer
enc := json.NewEncoder(&emptyAppendEntriesResponse)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
}
谢谢
英文:
I have a go code to encode struct to json object.
Can anybody show me how to decode it back?
The thing I don't understand is, to define decoder, what should it be as input?
package main
import "encoding/json"
import "bytes"
//import "os"
import "fmt"
func main() {
var emptyAppendEntriesResponse bytes.Buffer
enc := json.NewEncoder(&emptyAppendEntriesResponse)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
}
thanks
答案1
得分: 2
你可以使用bytes.Buffer
作为读取器和写入器,但如果你使用*bytes.Buffer
会更容易一些,因为你无论如何都需要使用指针。
emptyAppendEntriesResponse := bytes.NewBuffer(nil)
enc := json.NewEncoder(emptyAppendEntriesResponse)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
fmt.Println(string(emptyAppendEntriesResponse.Bytes()))
dec := json.NewDecoder(emptyAppendEntriesResponse)
d = map[string]int{}
dec.Decode(&d)
fmt.Printf("%+v\n", d)
当你不直接使用IO流时,通常使用json.Marshal
和json.Unmarshal
比创建Encoder和Decoder更方便。
d := map[string]int{"apple": 5, "lettuce": 7}
resp, err := json.Marshal(&d)
fmt.Println(string(resp))
d = map[string]int{}
err = json.Unmarshal(resp, &d)
fmt.Printf("%+v\n", d)
英文:
You can use a bytes.Buffer
as both a Reader and Writer, but it's a little easier if you use a *bytes.Buffer
, since you need to use a pointer anyway.
http://play.golang.org/p/NbK_D-bMML
emptyAppendEntriesResponse := bytes.NewBuffer(nil)
enc := json.NewEncoder(emptyAppendEntriesResponse)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
fmt.Println(string(emptyAppendEntriesResponse.Bytes()))
dec := json.NewDecoder(emptyAppendEntriesResponse)
d = map[string]int{}
dec.Decode(&d)
fmt.Printf("%+v\n", d)
When you're not working directly with io streams, it's usually more convenient to use json.Marshal
and json.Unmarshal
, rather than creating the Encoder and Decoder.
d := map[string]int{"apple": 5, "lettuce": 7}
resp, err := json.Marshal(&d)
fmt.Println(string(resp))
d = map[string]int{}
err = json.Unmarshal(resp, &d)
fmt.Printf("%+v\n", d)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论