Golang编码/解码JSON时添加null。

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

Golang encoding/json marshall add null

问题

你好,我是你的中文翻译助手。以下是你要翻译的内容:

嗨,我正在使用Golang编写编码/解码JSON的代码,但返回的JSON错误值为null:

{"user_message":"无法找到符合这些参数的任何查询","application_context":"GroupsRepository.GetGroupsByQuery: ApplicationError: UserMessage - Error querying database for many Groups. ApplicationContext - Groups.GetMany: pq: column \"refill_too_soon_gpi_digits\" does not exist"} null

我使用的编组方法如下:

func EncodeErrorResponse(w http.ResponseWriter, err error, status int) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(err)
}

请问有人可以帮助我吗?

英文:

Hi i am working with golang on encoding/json and it return the json error with null:

{"user_message":"Can't find any Query with those parameters","application_context":"GroupsRepository.GetGroupsByQuery: ApplicationError: UserMessage - Error querying database for many Groups. ApplicationContext - Groups.GetMany: pq: column \"refill_too_soon_gpi_digits\" does not exist"} null

and the way that i marshall that it is:

func EncodeErrorResponse(w http.ResponseWriter, err error, status int) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(err)
}

could someone help me please.

答案1

得分: 0

从你引用的JSON输出来看,错误已经被正确编码,但是在JSON之后输出了null,这表明有一个单独的写操作。调用EncodeErrorResponse的函数在调用它之后,向ResponseWriter写入了额外的输出。

英文:

Looking at the JSON output you quoted, it looks like the error is being encoded correctly, but null is being output after the JSON, indicating a separate write operation. The function that calls EncodeErrorResponse, after it calls it, is writing additional output to the ResponseWriter.

huangapple
  • 本文由 发表于 2017年7月7日 05:26:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/44959143.html
匿名

发表评论

匿名网友

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

确定