在这种情况下,JSON解码器的定义是什么?输入应该是什么?

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

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.Marshaljson.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)

huangapple
  • 本文由 发表于 2014年8月26日 23:33:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/25509741.html
匿名

发表评论

匿名网友

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

确定