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 vs2022无法联网
  • ¥15 TCP的客户端和服务器的互联
  • ¥15 VB.NET操作免驱摄像头
  • ¥15 笔记本上移动热点开关状态查询
  • ¥85 类鸟群Boids——仿真鸟群避障的相关问题
  • ¥15 CFEDEM自带算例错误,如何解决?
  • ¥15 有没有会使用flac3d软件的家人
  • ¥20 360摄像头无法解绑使用,请教解绑当前账号绑定问题,
  • ¥15 docker实践项目
  • ¥15 利用pthon计算薄膜结构的光导纳