草庐IT

json - 解码 JSON 时出错

coder 2023-07-02 原文

在过去的几天里,我第一次尝试使用 GO。

我有一个 HTML 表单,可以将它的值传递给服务器。该服务器依次提取表单键/值并将它们放入 JSON 中。然后将此 JSON 发送到另一台服务器。

问题是:当第二台服务器尝试解码 JSON 时出现以下错误:

JSON 解码错误:json:无法将字符串解码为 main.NewContainerJSON 类型的 Go 值

1:原始的HTML表单

<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:第一个服务器代码

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:第二台服务器代码:

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())

    }
}

错误发生在第二个服务器代码中的以下代码

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

fmt.Println(b)

我怀疑我没有正确解码 JSON 或者我遗漏了一些非常明显的东西。

最佳答案

第一台服务器对值进行双重编码。结果是一个字符串。

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

将代码更改为:

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
}

关于json - 解码 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36322527/

有关json - 解码 JSON 时出错的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby-on-rails - Rails HTML 请求渲染 JSON - 2

    在我的Controller中,我通过以下方式在我的index方法中支持HTML和JSON:respond_todo|format|format.htmlformat.json{renderjson:@user}end在浏览器中拉起它时,它会自然地以HTML呈现。但是,当我对/user资源进行内容类型为application/json的curl调用时(因为它是索引方法),我仍然将HTML作为响应。如何获取JSON作为响应?我还需要说明什么? 最佳答案 您应该将.json附加到请求的url,提供的格式在routes.rb的路径中定义。这

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby-on-rails - 如何使用 Rack 接收 JSON 对象 - 2

    我有一个非常简单的RubyRack服务器,例如:app=Proc.newdo|env|req=Rack::Request.new(env).paramspreq.inspect[200,{'Content-Type'=>'text/plain'},['Somebody']]endRack::Handler::Thin.run(app,:Port=>4001,:threaded=>true)每当我使用JSON对象向服务器发送POSTHTTP请求时:{"session":{"accountId":String,"callId":String,"from":Object,"headers":

  6. ruby - 使用 postgres.app 在 rvm 下要求 pg 时出错 - 2

    我正在使用Postgres.app在OSX(10.8.3)上。我已经修改了我的PATH,以便应用程序的bin文件夹位于所有其他文件夹之前。Rammy:~phrogz$whichpg_config/Applications/Postgres.app/Contents/MacOS/bin/pg_config我已经安装了rvm并且可以毫无错误地安装pggem,但是当我需要它时我得到一个错误:Rammy:~phrogz$gem-v1.8.25Rammy:~phrogz$geminstallpgFetching:pg-0.15.1.gem(100%)Buildingnativeextension

  7. ruby-on-rails - 为什么在安装 Ruby 1.9.3 时出现 404 错误? - 2

    我最近对我的计算机(OS-MacOSX10.6.8)进行了删除,并且我正在重新安装我所有的开发工具。我再次安装了RVM;但是,它不会让我安装Ruby1.9.3。到目前为止我已经尝试过:rvminstall1.9.3rvm安装1.9.3-p194rvm安装1.9.3-p448rvminstall1.9.3--with-gcc=clang所有返回相同的命令行错误:Searchingforbinaryrubies,thismighttakesometime.Nobinaryrubiesavailablefor:osx/10.6/x86_64/ruby-1.9.3-p448.Continuin

  8. ruby - 用 YAML.load 解析 json 安全吗? - 2

    我正在使用ruby2.1.0我有一个json文件。例如:test.json{"item":[{"apple":1},{"banana":2}]}用YAML.load加载这个文件安全吗?YAML.load(File.read('test.json'))我正在尝试加载一个json或yaml格式的文件。 最佳答案 YAML可以加载JSONYAML.load('{"something":"test","other":4}')=>{"something"=>"test","other"=>4}JSON将无法加载YAML。JSON.load("

  9. objective-c - 在设置 Cocoa Pods 和安装 Ruby 更新时出错 - 2

    我正在尝试为我的iOS应用程序设置cocoapods但是当我执行命令时:sudogemupdate--system我收到错误消息:当前已安装最新版本。中止。当我进入cocoapods的下一步时:sudogeminstallcocoapods我在MacOS10.8.5上遇到错误:ERROR:Errorinstallingcocoapods:cocoapods-trunkrequiresRubyversion>=2.0.0.我在MacOS10.9.4上尝试了同样的操作,但出现错误:ERROR:Couldnotfindavalidgem'cocoapods'(>=0),hereiswhy:U

  10. ruby-on-rails - 使用 Rails 2.3.5 运行 Thinking Sphinx 时出现问题 - 2

    我刚刚安装了Sphinx(发行版:archlinux)并下载了源代码。然后我为Rails安装了“ThinkingSphinx”插件。我关注了officialpagesetup和thisScreencastfromRyanBates,但是当我尝试为模型建立索引时,出现了这个错误:$rakethinking_sphinx:index(in/home/benoror/Dropbox/Proyectos/cotizahoy)Sphinxcannotbefoundonyoursystem.Youmayneedtoconfigurethefollowingsettingsinyourconfig/

随机推荐