duanqiang6501 2017-03-27 09:17
浏览 58
已采纳

Golang通用JSON编组

I'm working on s small server-client project based on JSON communication. But i run into issues. I'm trying to create a response struct with a generic message body. This means I have an map with a key as string and a json raw message as value. In the end the message body should work for any type (strings, integers, arrays)

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))
   }
}

But the output is as follow.

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

It seems like the values are Base64 encoded and inside double quotes. Tihs should be the expected output

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

Is this even possible? Or do I have to write a specific struct type for every response?

  • 写回答

1条回答 默认 最新

  • 普通网友 2017-03-27 11:32
    关注

    The raw message must be valid JSON.

    Add quotes to the string to make it a valid JSON string.

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

    JSON numbers are a sequence of decimal bytes. A number is not the value of a single byte as attempted in the question.

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

    This one works as you expected.

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

    The program in the question compiles and runs with errors. Examining those errors and fixing them leads to my suggestions above.

    An alternative approach is to replace the use of json.RawMessage with interface{}:

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

    Set the response body like this:

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

    You can use json.RawMessage values:

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

    Playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划