Json不能解组结构

I've got a situation, where I want to transfer messages with a TCP Connection from one server to another. I've created a struct on both servers:

type DataTransferObject struct {
    Name  string `json:"name"`
    Value string `json:"value"`
}

and with

dto := DataTransferObject{
    Name:  "Name",
    Value: name,
}

jsonDTO, _ := json.Marshal(dto)
connection.Write(jsonDTO)

I'm sending it to the other server. The server receives a message, but when I try to unmarshal it like this:

var MessageData DataTransferObject

        err = json.Unmarshal(message, &MessageData)
        fmt.Println(err.Error())

the MessageData struct stays nil. However when I print the message with

fmt.Println(string(message))

I get a string like this : {"Name":"testname","Value":"testvalue"}

Looks like the problem you are encountering is because json.Unmarshal doesn't handle the string termination in the byte array (this actually looks like a bug to me, if it expects a byte array it should know how to deal with it). So when you are allocating a 1024 byte buffer and read into it from connection, you end up with a few characters of data, null byte terminator and whatever garbage the rest of the buffer is. And that confuses json.Unmarshall. It actually throws an error about it and if you didn't ignore your error handling you would see it :)

Public Service Announcement: if something returns an error, you might want to at least print it. You will thank yourself later when shit breaks.

There are a few ways of dealing with it, but it seems that the standard is to use bufio library. Here is a complete, working example sending a JSON record down the TCP connection and de-serializing it into a struct (yes, this code completely ignores all errors)

package main

import (
    "bufio"
    "encoding/json"
    "fmt"
    "net"
    "time"
)

type DataTransferObject struct {
    Name  string `json:"name"`
    Value string `json:"value"`
}

func server(l net.Listener) {
    for {
        c, _ := l.Accept()
        data, _ := bufio.NewReader(c).ReadBytes(0)
        fmt.Printf("read %v bytes from the server
", len(data))
        fmt.Println("data: ", string(data))
        var obj DataTransferObject
        err := json.Unmarshal(data, &obj)
        if err != nil {
            fmt.Println(err)
        }
        fmt.Printf("Got object %+v
", obj)
    }
}

func main() {
    l, _ := net.Listen("tcp", ":8080")
    defer l.Close()
    go server(l)
    con, _ := net.Dial("tcp", "localhost:8080")
    data := []byte(`{"name": "Mad Wombat", "value": "Awesome Go Marsupial"}`)
    count, _ := con.Write(data)
    fmt.Printf("written %v bytes to the server
", count)
    con.Close()
    time.Sleep(time.Second) // wait for the server to do its thing
}

The struct in both projects:

type DataTransferObject struct {
    Name  string `json:"name"`
    Value string `json:"value"`
}

this is the complete code for receiving:

/**
* function for receiving a message with data from a client
**/
func (manager *ClientManager) receive(client *Client) {
    for {
        message := make([]byte,1024)
        length, err := client.socketConnection.Read(message)


        if err != nil {
            fmt.Println(err)
            manager.unregister <- client
            client.socketConnection.Close()
            break
        }

        if length > 0 {
            var MessageData DataTransferObject

            err = json.Unmarshal(message, &MessageData)
            fmt.Println(err.Error())

            if MessageData.Name =="Name"{
                manager.clientAddr[MessageData.Value] = client
                manager.SendData("testMessage", "hello world!")
            }else {
                fmt.Println(string (message))
            }

            manager.broadcast <- message
        }
    }
}

this is the complete function for sending data:

func StartClient() {
    scanner := bufio.NewScanner(os.Stdin)
    fmt.Print("Please Insert a name: ")

    for scanner.Scan() {
    name = scanner.Text()
        fmt.Println("Name is now: " + name)
        if len(name) > 0 {
            break;
        }
    }

    if scanner.Err() != nil {

    }

    fmt.Println("Starting client...")
    connection, error := net.Dial("tcp", "localhost:4242")

    if error != nil {
        fmt.Println(error)
    }
    client := &Client{socket: connection}
    go client.receive()
    dto := DataTransferObject{
        Name:  "Name",
        Value: name,
    }

    jsonDTO, _ := json.Marshal(dto)
    connection.Write(jsonDTO)

}