在Go语言中,使用JSON编码时无法获取正确的数据。

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

Not getting proper data using json encoding for a structure in go language

问题

//package cluster
package main

import (
"encoding/csv"
"encoding/json"
"fmt"
"io"
"math/rand"
"net"
"os"
"strconv"
"time"
//"bytes"
)

const (
BROADCAST = -1
)

var outbox, inbox chan *Envelope
var pids [10]int
var ips [10]string

type Envelope struct {
Pid int
MsgId int64
Msg interface{}
}

type Server interface {
Pid() int
Peers() []int
Outbox() chan *Envelope
Inbox() chan *Envelope
}

/*
func (envelope Envelope) Pid() int {
return envelope.MsgId
}
*/
var server Envelope

func (envelope Envelope) Peers() []int {
return nil //pids
}

func (envelope Envelope) Outbox() chan *Envelope {
return outbox
}

func (envelope Envelope) Inbox() chan *Envelope {
return inbox
}

func server_() {
// listen on a port
ln, err := net.Listen("tcp", ":9999")
//time.Sleep(time.Second * 2)
if err != nil {
fmt.Println(err)
return
}
for {
c, err := ln.Accept()
if err != nil {
fmt.Println(err)
continue
} else {
fmt.Println("handle")
go handleServerConnection(c)
}
}
}

func handleServerConnection(c net.Conn) {
// receive the message
var msg Envelope
var b []byte
// for{
c.Read(b)
/*
if b == nil{
continue
}else{
break
}
*/
// }

fmt.Println(b)
err := json.Unmarshal(b, &msg)
if err != nil { //ERORR !!!!
	fmt.Println(err)
} else {
	fmt.Println("Received : %+v", msg)
}
c.Close()

}

func client() {
// connect to the server
for msg := range outbox {
c, err := net.Dial("tcp", "127.0.0.1:9999")
if err != nil {
fmt.Println(err)
return
}

	if err != nil {
		fmt.Println("error encoding the response to a join request")
		fmt.Println(err)
	}
	b, _ := json.Marshal(msg)
	fmt.Printf("the json: %s\n", b)
	c.Write(b)
	c.Close()
}
time.Sleep(time.Second * 2)

}

func New(myPid int, ConFile string) Envelope {
inbox = make(chan *Envelope, 100)
outbox = make(chan *Envelope, 100)
file, err := os.Open(ConFile)
if err != nil {
fmt.Println("Error:", err)
}
defer file.Close()
reader := csv.NewReader(file)

i := 0
j := 0
for {
	record, err := reader.Read()
	if err == io.EOF {
		break
	} else if err != nil {
		fmt.Println("Error:", err)
	}
	x, _ := strconv.Atoi(record[0])
	pids[i] = x
	i++
	ips[j] = record[1]
	j++
}

fmt.Println("\n", ips)
fmt.Println("\n", pids)
MsgId := rand.Int63n(0x10000000)
server = Envelope{Pid: myPid, MsgId: MsgId, Msg: "Hello World :)"}

go server_()
go client()
var input string
fmt.Println("\n\nPress enter ---\n\n")
fmt.Scanln(&input)
return server

}

func main() {
//for i := 1; i < 10; i++ {
server := New(12, "config.txt")

server.Outbox() <- &Envelope{Pid: BROADCAST, MsgId: server.MsgId, Msg: "hello there"}
select {
case envelope := <-server.Inbox():
	fmt.Printf("Received msg from %d: '%s'\n", envelope.Pid, envelope.Msg)

case <-time.After(2 * time.Second):
	println("Waited and waited. Ab thak gaya\n")
}

//fmt.Println(server.Pid, server.MsgId, server.Msg )
//}

}

英文:
//package cluster
package main

import (
&quot;encoding/csv&quot;
&quot;encoding/json&quot;
&quot;fmt&quot;
&quot;io&quot;
&quot;math/rand&quot;
&quot;net&quot;
&quot;os&quot;
&quot;strconv&quot;
&quot;time&quot;
//&quot;bytes&quot;
)

const (
BROADCAST = -1
 )

var outbox, inbox chan *Envelope
var pids [10]int
var ips [10]string

type Envelope struct {
Pid   int
MsgId int64
Msg   interface{}
}

type Server interface {
Pid() int
Peers() []int
Outbox() chan *Envelope
Inbox() chan *Envelope
}

/*
func (envelope Envelope) Pid() int {
return envelope.MsgId
}
*/
var server Envelope

func (envelope Envelope) Peers() []int {
return nil //pids
}

func (envelope Envelope) Outbox() chan *Envelope {
return outbox
}

func (envelope Envelope) Inbox() chan *Envelope {
return inbox
}

func server_() {
// listen on a port
ln, err := net.Listen(&quot;tcp&quot;, &quot;:9999&quot;)
//time.Sleep(time.Second * 2)
if err != nil {
	fmt.Println(err)
	return
}
for {
	c, err := ln.Accept()
	if err != nil {
		fmt.Println(err)
		continue
	} else {
		fmt.Println(&quot;handle&quot;)
		go handleServerConnection(c)
	}
} 
}

func handleServerConnection(c net.Conn) {
// receive the message
var msg Envelope
var b []byte
//	for{
c.Read(b)
/*
	if b == nil{
		continue
	}else{
		break
	}
*/
//	}

fmt.Println(b)
err := json.Unmarshal(b, &amp;msg)
if err != nil { //ERORR !!!!
	fmt.Println(err)
} else {
	fmt.Println(&quot;Received : %+v&quot;, msg)
}
c.Close()
}

func client() {
// connect to the server
for msg := range outbox {
	c, err := net.Dial(&quot;tcp&quot;, &quot;127.0.0.1:9999&quot;)
	if err != nil {
		fmt.Println(err)
		return
	}

	if err != nil {
		fmt.Println(&quot;error encoding the response to a join request&quot;)
		fmt.Println(err)
	}
	b, _ := json.Marshal(msg)
	fmt.Printf(&quot;the json: %s\n&quot;, b)
	c.Write(b)
	c.Close()
}
time.Sleep(time.Second * 2)
}

func New(myPid int, ConFile string) Envelope {
inbox = make(chan *Envelope, 100)
outbox = make(chan *Envelope, 100)
file, err := os.Open(ConFile)
if err != nil {
	fmt.Println(&quot;Error:&quot;, err)
}
defer file.Close()
reader := csv.NewReader(file)

i := 0
j := 0
for {
	record, err := reader.Read()
	if err == io.EOF {
		break
	} else if err != nil {
		fmt.Println(&quot;Error:&quot;, err)
	}
	x, _ := strconv.Atoi(record[0])
	pids[i] = x
	i++
	ips[j] = record[1]
	j++
}

fmt.Println(&quot;\n&quot;, ips)
fmt.Println(&quot;\n&quot;, pids)
MsgId := rand.Int63n(0x10000000)
server = Envelope{Pid: myPid, MsgId: MsgId, Msg: &quot;Hello World :)&quot;}

go server_()
go client()
var input string
fmt.Println(&quot;\n\nPress enter ---\n\n&quot;)
fmt.Scanln(&amp;input)
return server
}

func main() {
//for i := 1; i &lt;= 10; i++ {
server := New(12, &quot;config.txt&quot;)

server.Outbox() &lt;- &amp;Envelope{Pid: BROADCAST, MsgId: server.MsgId, Msg: &quot;hello there&quot;}
select {
case envelope := &lt;-server.Inbox():
	fmt.Printf(&quot;Received msg from %d: &#39;%s&#39;\n&quot;, envelope.Pid, envelope.Msg)

case &lt;-time.After(2 * time.Second):
	println(&quot;Waited and waited. Ab thak gaya\n&quot;)
}

//fmt.Println(server.Pid, server.MsgId, server.Msg )
//}

}

From client function I am trying to send some data but unable to receive data in handleServerConnection()

my program is written in go language
help me out

I have referred most of the examples given in the book and stack overflow

i am getting an empty object in handleconnection function

答案1

得分: 0

你能分享一下你尝试解码的json的示例吗?我怀疑这是一个注释问题。大多数json都是小写的,因为它符合JavaScript的语法。

例如,我怀疑你的json看起来像这样:

{"pid":"0", "msgId":"500", "msg":"this is the message"}

如果是这种情况,那么你的结构体需要像这样添加注释:

type Envelope struct {
    Pid   int         `json:"pid"`
    MsgId int64       `json:"msgId"`
    Msg   interface{} `json:"msg"`
}

再次强调,没有示例的情况下,我只是猜测这可能是你的问题。

英文:

Can you share an example of the json you are trying to decode? I suspect that it is an annotations issue. Most json is lowercase due to the javascript syntax.

For instance, I suspect your json looks like this:

{&quot;pid&quot;:&quot;0&quot;, &quot;msgId&quot;:&quot;500&quot;, &quot;msg&quot;:&quot;this is the message&quot;}

If that is the case, then you need annotations on your struct like this:

type Envelope struct {
	Pid   int         `json:&quot;pid&quot;`
	MsgId int64       `json:&quot;msgId&quot;`
	Msg   interface{} `json:&quot;msg&quot;`
}

Again, without an example, I'm only guessing that this is your problem.

huangapple
  • 本文由 发表于 2014年1月27日 13:22:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/21373558.html
匿名

发表评论

匿名网友

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

确定