Help with encoding and decoding Json Data?

blov · 2017-03-18 00:00:10 · 625 次点击    
这是一个分享于 2017-03-18 00:00:10 的资源,其中的信息可能已经有所发展或是发生改变。

Hello all, I am trying to build a simple chat app to learn more about golang and am getting tripped up by json. When I try to decode I get no output and the "in" variable is empty. Here is my code so far for my client and server.

client:

func main() {
    out := Message{name: "Jacob", text: "hey whats up"}
    conn, err := net.Dial("tcp", "127.0.0.1:6666")
    if err != nil {
            panic(err)
    }
    err := json.NewEncoder(conn).Encode(&out)
    if err != nil {
            panic(err)
    }
}

server:

func main() {
    in := new(Message)
    server, _ := net.Listen("tcp", "127.0.0.1:6666")
    conn, _ := server.Accept()
    err := json.NewDecoder(conn).Decode(&in)
    if err != nil {
        panic(err)
    }   

    fmt.Println(in.name+":", in.text)
}

But when I run the two, my only output is ":". I know it has to be a dumb mistake, so any help or advice is appreciated!


评论:

Perelandric:

Go can't encode/decode private fields.


EDIT: Here's a working example with exported fields and field tags: https://play.golang.org/p/y-DmJ_iTPj

Eniac17:

THANK YOU. Oh my I've been freaking out over this for two hours and forgot how go handled private fields. Oh the wonders of learning a new language

Killing_Spark:

So your example works because you defined message explicitly as a type with those two fields?

Sorry if this question is dumb I just started reading up on go :)

Perelandric:

No, the Message type was just left out of the question. It worked because I made the fields of Message public, meaning they can be accessed by code outside of the package in which it was defined.

Fields are made public by starting their name with a capital letter. So in the original code, it would have looked like this:

type Message struct {
  name string
  text string
}

That defines a struct with two, private fields. Mine capitalizes those field names:

type Message struct {
  Name string
  Text string
}

So now they're readable/writable by any code that gets a value of that type.

This is necessary because the json package (or more accurately, the reflect package) can only work with fields that it can access.

Killing_Spark:

Ah I see. Thanks for the thorough answer :)

danredux:

code looks good but i think maybe you're using too many indirections? maybe?

in := new(Message) // in is now of type *Message
Decode(&in) // now you're passing **Message

same goes for your encode..


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

625 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传