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

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

报告相同问题?