Golang如何生成特定格式的JSON响应
Golang如何生成特定格式的JSON响应 我在调用我的Go语言API时,试图生成以下输出。
{
"jsonrpc": "2.0",
"result": [
false,
"",
"",
""
],
"id": 1
}
目前,使用
type JSONRpc struct {
Id json.RawMessage `json:"id,omitempty"`
Version string `json:"jsonrpc,omitempty"`
Result interface{} `json:"result"`
}
message := JSONRpc{Id: id, Version: "2.0", Result: fmt.Sprintf("[%t, %q, %q, %q]", false, "", "", "")}
Encode(&message)
以及
[%t, %s, %s, %s]
我能够得到
{
"id": 1,
"jsonrpc": "2.0",
"result": "[false, \"\", \"\", \"\"]"
}
和
{
"id": 1,
"jsonrpc": "2.0",
"result": "[false, , , ]"
}
我如何才能得到一个完美的
{
"jsonrpc": "2.0",
"result": [
false,
"",
"",
""
],
"id": 1
}
更多关于Golang如何生成特定格式的JSON响应的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
要生成特定格式的JSON响应,你需要正确定义Result字段的类型。当前使用interface{}配合fmt.Sprintf会导致字符串序列化,而不是JSON数组。以下是解决方案:
package main
import (
"encoding/json"
"fmt"
)
type JSONRpc struct {
ID json.RawMessage `json:"id,omitempty"`
Version string `json:"jsonrpc,omitempty"`
Result interface{} `json:"result"`
}
func main() {
// 方法1:使用切片直接定义
resultSlice := []interface{}{false, "", "", ""}
id, _ := json.Marshal(1)
message := JSONRpc{
ID: id,
Version: "2.0",
Result: resultSlice,
}
output, _ := json.MarshalIndent(message, "", " ")
fmt.Println(string(output))
// 方法2:自定义Result类型
type RPCResult []interface{}
type JSONRpc2 struct {
ID json.RawMessage `json:"id,omitempty"`
Version string `json:"jsonrpc,omitempty"`
Result RPCResult `json:"result"`
}
message2 := JSONRpc2{
ID: id,
Version: "2.0",
Result: RPCResult{false, "", "", ""},
}
output2, _ := json.MarshalIndent(message2, "", " ")
fmt.Println(string(output2))
}
输出结果:
{
"jsonrpc": "2.0",
"result": [
false,
"",
"",
""
],
"id": 1
}
关键点:
Result字段应该直接存储切片[]interface{}{false, "", "", ""},而不是格式化的字符串json.Marshal会自动将切片序列化为JSON数组- 使用
json.MarshalIndent可以获得格式化的JSON输出
如果需要处理更复杂的场景,可以定义具体的结构体类型:
type ResultItem struct {
Value interface{} `json:"value"`
}
type JSONRpc3 struct {
ID json.RawMessage `json:"id,omitempty"`
Version string `json:"jsonrpc,omitempty"`
Result []ResultItem `json:"result"`
}

