douyaju4259 2014-08-26 15:33
浏览 3
已采纳

进入json解码器定义,在这种情况下应作为输入

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条回答 默认 最新

  • dongpiao0731 2014-08-26 15:55
    关注

    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
    ", 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
    ", d)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题