无法在Go语言中解析JSON。

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

Unabled to parse JSON in go lang

问题

我正在尝试使用标签在golang中解析JSON。我没有任何错误,但是我的字段是空的。

这是我的代码:

type HandleConnection struct {
    session string `json:"session"`
    passwd  int   `json:"field1"`   
    salon string `json:"field2"`
    color string `json:"field3"`
    state float64 `json:"field4"`
    message string `json:"field5"`
}

func connection(login string, passwd string) (*HandleConnection, error) {

    jsonParsedResponse := &HandleConnection{}

    resp, err := http.PostForm(ajaxUrl, url.Values{
        "q": {"bar"}, 
        "v": {"foo"},
        "identifiant": {login},
        "motdepasse": {passwd},
        "mode": {"0"},
        "decalageHoraire": {"0"},
        "option": {""},
        "salon": {"foo"},
    })

    if err != nil {
        return jsonParsedResponse , err
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        return jsonParsedResponse, err
    }

    err = json.Unmarshal(body, &jsonParsedResponse)

    if err != nil {
        return jsonParsedResponse, err
    }

    if jsonParsedResponse.state != 2 {
        return jsonParsedResponse, errors.New(jsonParsedResponse.message)
    }

    return jsonParsedResponse, nil
}

返回的JSON如下:

{
  "field1": "foo",
  "field2": "bar",
  ...
}

我想知道在Go中处理错误的最佳方式是什么。

谢谢阅读。

英文:

I'm trying to parse JSON using tags with golang. I don't have any errors, but my field are empty

Here is my code :

type HandleConnection struct {
    session string `json:"session"`
	passwd  int   `json:"field1"`   
	salon string `json:"fied2"`
	color string `json:"field3"`
	state float64 `json:"field4"`
	message string `json:"field5"`

}

func connection(login string, passwd string) (*HandleConnection, error) {

	jsonParsedResponse := &HandleConnection{}

	resp, err := http.PostForm(ajaxUrl, url.Values{
		"q": {"bar"}, 
		"v": {"foo"},
		"identifiant": {login},
		"motdepasse": {passwd},
		"mode": {"0"},
		"decalageHoraire": {"0"},
		"option": {""},
		"salon": {"foo"},
	})

	if err != nil {
		return jsonParsedResponse , err
    }

    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)

    if err != nil {
        return jsonParsedResponse, err
    }

    err = json.Unmarshal(body, &jsonParsedResponse)

    if err != nil {
    	return jsonParsedResponse, err
    }

    if jsonParsedResponse.state != 2 {
    	return jsonParsedResponse, errors.New(jsonParsedResponse.message)
    }

    return jsonParsedResponse, nil
}

the returned json is like that

{
  "field1": "foo",
  "fiel2": "bar",
  ...
}

And I would like to know what's the better way for error handling in go.

Thanks for reading

答案1

得分: 5

你正在犯一个常见的错误,即在你的结构体中有未导出的字段。

encoding/json 包中指出(我强调):

结构体值被编码为 JSON 对象。每个导出的结构体字段都成为对象的成员,除非

  • 字段的标签是“-”,或者
  • 字段为空并且其标签指定了“omitempty”选项。

这是因为 Go 不允许对未导出的字段进行反射。
如果你将你的结构体更改为以下形式,应该可以工作:

type HandleConnection struct {
    Session string  `json:"session"`
    Passwd  int     `json:"field1"`
    Salon   string  `json:"field2"`
    Color   string  `json:"field3"`
    State   float64 `json:"field4"`
    Message string  `json:"field5"`
}
英文:

You are doing the common mistake of having unexported fields in your struct.

The encoding/json package states (my emphasis):

>Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless
>
>- the field's tag is "-", or
>- the field is empty and its tag specifies the "omitempty" option.

This is due to Go not allowing reflection on unexported fields.
It should work if you change your struct to the following:

type HandleConnection struct {
	Session string  `json:"session"`
	Passwd  int     `json:"field1"`
	Salon   string  `json:"fied2"`
	Color   string  `json:"field3"`
	State   float64 `json:"field4"`
	Message string  `json:"field5"`
}

答案2

得分: -1

你需要以大写字母开头来定义结构体的属性,这样它们才能是公共的,且反序列化可以访问这些字段。

英文:

You need to start the struct attributes with Capitals so they are public and unmarshaling has access to those fields.

huangapple
  • 本文由 发表于 2013年11月20日 23:05:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/20099472.html
匿名

发表评论

匿名网友

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

确定