相关疑难解决方法(0)

为什么Golang不能从具有前小写字符的struct生成json?

我试图从我创建的结构中打印json结果,如下所示:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}
Run Code Online (Sandbox Code Playgroud)

并打印出来

m:= &Machine{ m_ip:"test", m_type:"test", m_serial:"test" }
m_json:= json.Marshal(m)
fmt.Println(m_json)
Run Code Online (Sandbox Code Playgroud)

但是,结果返回{}

其次,我尝试将单词的第一个字母改为大写,如下所示:

type Machine struct{
  MachIp string
  MachType string
  MachSerial string
}
Run Code Online (Sandbox Code Playgroud)

它的工作原理!无论如何,为什么前面的小写字母不起作用?

go goroutine

31
推荐指数
1
解决办法
8776
查看次数

我的结构不是编组到json中

我在Mac OS X 10.8.2上使用Go 1.0.3,我正在试验json包,尝试将结构封送到json,但我不断得到一个空的{}json对象.

err值是零,所以没有什么根据的是错误的json.Marshal功能,并且该结构是正确的.为什么会这样?

package main

import (
  "encoding/json"
  "fmt"
)

type Address struct {
  street string
  extended string
  city string
  state string
  zip string
}

type Name struct {
  first string
  middle string
  last string
}

type Person struct {
  name Name
  age int
  address Address
  phone string
}

func main() {
  myname := Name{"Alfred", "H", "Eigenface"}
  myaddr := Address{"42 Place Rd", "Unit 2i", "Placeton", "ST", "00921"}
  me := …
Run Code Online (Sandbox Code Playgroud)

json go

17
推荐指数
2
解决办法
1504
查看次数

Golang:json.Unmarshal没有正确返回数据

我有一个json文件(themes/snow/theme.json)

{
    Name:'snow',
    Bgimage:'background.jpg',
    Width:600,
    Height:400,
    Itemrotation:'20,40',
    Text:{
        Fontsize:12,
        Color:'#ff00ff',
        Fontfamily:'verdana',
        Bottommargin:20
    },
    Decoration:[
        {
            Path:'abc.jpg',
            X:2,
            Y:4,
            Rotation:0
        },
        {
            Path:'def.png',
            X:4,
            Y:22,
            Rotation:10
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

我有一个解析json数据的文件

package main

import (
    "fmt"
    "os"
    "encoding/json"
    "io/ioutil"
    "log"
)

const themeDirectory    = "themes"
const themeJsonFile     = "theme.json"

type TextInfo struct {
    Fontsize        int
    Color           string
    Fontfamily      string
    Bottommargin    int
}

type DecoInfo struct {
    Path            string
    X               int
    Y               int
    Rotation        int
}

type ThemeInfo struct {
    Name            string
    Bgimage …
Run Code Online (Sandbox Code Playgroud)

json go

4
推荐指数
2
解决办法
6637
查看次数

在 Go 中解组通用 json

我是一名新的 Go 程序员(来自 Java),我想重现一种在 Java 中易于使用的通用方式。

我想创建一些函数,允许我对 JSON 字符串执行解组,以避免代码重复。

这是我当前不起作用的代码:

type myStruct1 struct {
    id string
    name string
}

func (obj myStruct1) toString() string {
    var result bytes.Buffer
    result.WriteString("id : ")
    result.WriteString(obj.id)
    result.WriteString("\n")
    result.WriteString("name : ")
    result.WriteString(obj.name)

    return result.String()
}

func main() {

    content := `{id:"id1",name="myName"}`
    object := myStruct1{}
    parseJSON(content, object)

    fmt.Println(object.toString()) 
}

func parseJSON(content string, object interface{}) {
    var parsed interface{}
    json.Unmarshal([]byte(content), &parsed)
}
Run Code Online (Sandbox Code Playgroud)

这段代码在运行时返回给我:

id : 
name : 
Run Code Online (Sandbox Code Playgroud)

你有什么主意吗 ?

谢谢

json go

4
推荐指数
3
解决办法
9590
查看次数

结果打印空Json

我试图从我的postgres数据库中检索一些数据并将它们打印localhost/db为json.我成功地在没有json的情况下打印它们,但我需要它们在json中.

main.go:

package main

import (
    "database/sql"
    "encoding/json"
    "fmt"
    "log"
    "net/http"

    _ "github.com/lib/pq"
)

type Book struct {
    isbn   string
    title  string
    author string
    price  float32
}

var b []Book

func main() {

    db, err := sql.Open("postgres", "postgres://****:****@localhost/postgres?sslmode=disable")

    if err != nil {
        log.Fatal(err)
    }
    rows, err := db.Query("SELECT * FROM books")
    if err != nil {
        log.Fatal(err)
    }
    defer rows.Close()

    var bks []Book
    for rows.Next() {
        bk := new(Book)
        err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price)
        if err …
Run Code Online (Sandbox Code Playgroud)

encoding json go

4
推荐指数
1
解决办法
550
查看次数

去json.Unmarshal不工作

我有json未解码为struct.

我知道我的代码中的错误,但我被卡住了,不知道错误在哪里以及我做错了什么

请帮帮我,这是我的代码:

type GOOGLE_JSON struct {
    code        string `json:"code"`
    clientId    string `json:"clientId"`
    redirectUri string `json:"redirectUri"`
}

body := []byte(`{"code":"111","clientId":"222","redirectUri":"333"}`)

//google_json := GOOGLE_JSON{}
var google_json GOOGLE_JSON

err := json.Unmarshal(body, &google_json)
if err != nil {
    fmt.Println(err)
}
fmt.Println(google_json)
Run Code Online (Sandbox Code Playgroud)

这里的例子

json go unmarshalling

3
推荐指数
1
解决办法
848
查看次数

Beego控制器中的JSON响应

我是一个尝试在路线上获得JSON响应的新手.

我有一个如此定义的控制器.

package controllers

import (
    "github.com/astaxie/beego"
)

type ErrorController struct {
    beego.Controller
}

type ErrorJson struct {
    s string
    d string
}

func (this *ErrorController) Get() {

    var responseJson ErrorJson
    responseJson = ErrorJson{
        s: "asdf",
        d: "qwer",
    }

    this.Data["json"] = responseJson
    this.ServeJson()
}
Run Code Online (Sandbox Code Playgroud)

我的路由器定义为

beego.Router("/api", &controllers.ErrorController{})
Run Code Online (Sandbox Code Playgroud)

当我访问路径时,我得到一个没有任何属性的Empty JSON对象.

{}
Run Code Online (Sandbox Code Playgroud)

如果我用字符串替换json结构,我会得到一个响应.所以beego知道控制器和方法.

this.Data["json"] = "Hello World"
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

json struct go beego

3
推荐指数
1
解决办法
3541
查看次数

go中的元帅递归类型

我希望Marshal和Unmarshal是递归类型,如下所示:

type Dog struct {
    age int
    sibling *Dog
}
Run Code Online (Sandbox Code Playgroud)

在golang有什么办法吗?我试过json.Marshal,但它不起作用.

marshalling go unmarshalling

3
推荐指数
1
解决办法
555
查看次数

如何在golang中解组json

我有一个 json:

{"code":200,
 "msg":"success",
 "data":{"url":"https:\/\/mp.weixin.qq.com\/cgi-bin\/showqrcode?ticket=gQHQ7jwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyX3pqS0pMZlA4a1AxbEJkemhvMVoAAgQ5TGNYAwQsAQAA"}}
Run Code Online (Sandbox Code Playgroud)

我定义了一个结构:

type Result struct {
    code int
    msg  string                 `json:"msg"`
    data map[string]interface{} `json:"data"`
}
Run Code Online (Sandbox Code Playgroud)

对于这段代码:

var res Result
json.Unmarshal(body, &res)
fmt.Println(res)
Run Code Online (Sandbox Code Playgroud)

输出是:{0 map[]}

我想进去urldata怎么进去?

json go

3
推荐指数
1
解决办法
3285
查看次数

JSON 编码返回空白 Golang

我的服务器中有一个非常简单的 http 响应,我在其中对结构进行了 json 编码。但它发送的只是一个空白{}

我不知道我是否做错了,但我没有错误。这是我的 json 编码:

    // Set uuid as string to user struct
    user := User{uuid: uuid.String()}
    fmt.Println(user) // check it has the uuid

    responseWriter.Header().Set("Content-Type", "application/json")
    responseWriter.WriteHeader(http.StatusCreated)

    json.NewEncoder(responseWriter).Encode(user)
Run Code Online (Sandbox Code Playgroud)

在接收端,数据有:

Content-Type application/json
Content-Length 3
STATUS HTTP/1.1 201 Created
{}
Run Code Online (Sandbox Code Playgroud)

为什么它不给我 uuid 数据?我的编码有问题吗?

json httpresponse go

3
推荐指数
1
解决办法
1560
查看次数