dqoag62688 2016-03-31 01:14
浏览 196
已采纳

解码JSON时出错

I have been experimenting with GO for the first time, over the last few days.

I have a HTML form that passes it's values to a server. This server in turn extracts the form keys/ values and places them inside a JSON. This JSON is then sent to another server.

The issue is: I get the following error when the second server attempts to decode the JSON:

Error decoding JSON: json: cannot unmarshal string into Go value of type main.NewContainerJSON

1: The original HTML form

<form method="post" action="http://127.0.0.1:8080/new-user" autocomplete ="on">
<table>
    <tr>
        <td colspan="2"><h1>Container Configuration</h1></td>
    </tr>
    <tr>
        <td><h2>Container Name</h2></td>
        <td><input type="text" name="containerName" placeholder = "My Container Name" required /></td>
    </tr>
    <tr>
        <td><h2>Base Server</h2></td>
        <td>
            <select name="BaseServer">
                <option value="Ubuntu 14.04">Ubuntu 14.04</option>
        </td>
    </tr>
    <tr>
        <td><h2>Content Management System</h2></td>
        <td>
            <select name="CMS">
                <option value="Wordpress">Wordpress</option>
        </td>
    </tr>
    <tr>
        <td><h2>Website Name</h2></td>
        <td><input type="text" name="websiteName" placeholder = "mysite.com" required /></td>
    </tr>
    <tr>
        <td><h2>New Root Database Password</h2> </td>
        <td><input type = "password" name = "dbRootPWD" placeholder = "password" required /></td>
    </tr>
    <tr>
        <td><h2>Database Admin Username</h2></td>
        <td><input type = "text" name = "dbAdminUname" placeholder = "Admin" required /></td>
    </tr>
    <tr>
        <td><h2>Database Admin Password</h2></td>
        <td><input type = "password" name = "dbAdminPwd" placeholder = "password" required /></td>
    </tr>
    <tr>
        <td></td>
        <td><input type = "submit" value = "submit"></td>
    </tr>
</table>    

2: The first servers code

package main

import (
"fmt"
"encoding/json"
"net"
"net/http"
 )

type newContainerJSON struct {
    ContainerName string
    BaseServer string
    CMS string
    WebsiteName string
    DBrootPWD string
    DBadminUname string
    DBadminPWD string
}

func newUser(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()

    cName := r.FormValue("containerName")
    sName := r.FormValue("BaseServer")
    cmsName := r.FormValue("CMS")
    wsName := r.FormValue("websiteName")
    dbrootPwd := r.FormValue("dbRootPWD")
    dbadmName := r.FormValue("dbAdminUname")
    dbamdpwdName := r.FormValue("dbAdminPwd") 

    c := newContainerJSON {
        ContainerName: cName,
        BaseServer: sName,
        CMS: cmsName,
        WebsiteName: wsName,
        DBrootPWD: dbrootPwd,
        DBadminUname: dbadmName,
        DBadminPWD: dbamdpwdName,
    }

    d, _ := json.Marshal(c)
    s := string(d)
    fmt.Println(s)

    conn, err := net.Dial("tcp", "127.0.0.1:8081")
    checkError(err)

    encoder := json.NewEncoder(conn)

    encoder.Encode(d) 
}

func main() {
    http.HandleFunc("/new-user", newUser)
    err := http.ListenAndServe(":8080", nil) // setting listening port
    checkError(err)
}

func checkError(err error) {
    if err != nil {
        fmt.Println("Fatal error ", err.Error())
     }
}

3: The second servers code:

package main

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

type NewContainerJSON struct {
    ContainerName string    `json:",string"`
    BaseServer string       `json:",string"`
    CMS string              `json:",string"`
    WebsiteName string      `json:",string"`
    DBrootPWD string        `json:",string"`
    DBadminUname string     `json:",string"`
    DBadminPWD string       `json:",string"`
}

func main() {

    service := "127.0.0.1:8081"
    tcpAddr, err := net.ResolveTCPAddr("tcp", service)
    checkError(err)

    listener, err := net.ListenTCP("tcp", tcpAddr)
    checkError(err)

    conn, err := listener.Accept()
    checkError(err)

    decoder := json.NewDecoder(conn)

    var b NewContainerJSON
    err = decoder.Decode(&b)
    checkError(err)

    fmt.Println(b)

    conn.Close() // we're finished

}

func checkError(err error) {
    if err != nil {
        fmt.Println("An error occurred: ", err.Error())

    }
}

The error occurs with following code in the second servers code

var b NewContainerJSON
err = decoder.Decode(&b)
checkError(err)

fmt.Println(b)

I suspect I am not decoding the JSON properly or I am missing something very obvious.

  • 写回答

2条回答 默认 最新

  • dongmai6666 2016-03-31 02:01
    关注

    The first server is double encoding the value. The result is a string.

    d, _ := json.Marshal(c) // d is []byte containing the JSON
    ...
    encoder.Encode(d)  // encoder writes base64 encoding of []byte as JSON string
    

    Change the code to:

    conn, err := net.Dial("tcp", "127.0.0.1:8081")
    if err != nil {
         // handle error
    }
    encoder := json.NewEncoder(conn)
    if err := encoder.Encode(c); err != nil {
       // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集