Golang通用JSON编组

时间:2017-03-27 09:17:47

标签: arrays json go marshalling

我正在开发基于JSON通信的小型服务器客户端项目。但我遇到了问题。我试图用通用消息体创建响应结构。这意味着我有一个地图,其中一个键作为字符串,一个json原始消息作为值。最后,消息体应该适用于任何类型(字符串,整数,数组)

package main

import (
   "encoding/json"
   "fmt"
)

type ServerResponse struct {
    Code int                    `json:"code" bson:"code"`
    Type string                 `json:"type" bson:"type"`
    Body map[string]json.RawMessage `json:"body" bson:"body"`
}

func NewServerResponse() *ServerResponse {
    return &ServerResponse{Body: make(map[string]json.RawMessage)}
}





func main(){
    serverResponse := NewServerResponse()
    serverResponse.Code = 100
    serverResponse.Type = "molly"

    serverResponse.Body["string"] = json.RawMessage("getIt")
    serverResponse.Body["integer"] = json.RawMessage{200}
    serverResponse.Body["array"] = json.RawMessage(`["a", "b", "c"]`)


    if d, err  := json.Marshal(&serverResponse); err != nil{
        fmt.Println("Error " + err.Error())
    }else{
        fmt.Println(string(d))
   }
}

但输出结果如下。

{
  "code":100,
  "type":"molly",
  "body":  {
            "array":"WyJhIiwgImIiLCAiYyJd",
            "integer":"yA==",
            "string":"Z2V0SXQ="
           }
}

似乎值是Base64编码和双引号内。 Tihs应该是预期的输出

{
  "code":100,
  "type":"molly",
  "body":  {
            "array":["a", "b", "c"],
            "integer":200,
            "string":"getIt"
           }
}

这甚至可能吗?或者我是否必须为每个响应编写特定的结构类型?

1 个答案:

答案 0 :(得分:0)

原始邮件必须是有效的JSON。

在字符串中添加引号,使其成为有效的JSON字符串。

serverResponse.Body["string"] = json.RawMessage("\"getIt\"")

JSON编号是十进制字节序列。数字不是问题中尝试的单个字节的值。

serverResponse.Body["integer"] = json.RawMessage("200")

这个按预期工作。

serverResponse.Body["array"] = json.RawMessage(`["a", "b", "c"]`)

问题中的程序编译并运行时出错。检查这些错误并修复它们会导致我的上述建议。

另一种方法是将json.RawMessage替换为interface{}

type ServerResponse struct {
  Code int                    `json:"code" bson:"code"`
  Type string                 `json:"type" bson:"type"`
  Body map[string]interface{} `json:"body" bson:"body"`
}

像这样设置响应体:

serverResponse.Body["string"] = "getIt"
serverResponse.Body["integer"] = 200
serverResponse.Body["array"] = []string{"a", "b", "c"}

您可以使用json.RawMessage值:

serverResponse.Body["array"] = json.RawMessage(`["a", "b", "c"]`)

Playground example