首页 > 解决方案 > 如何将 struct 转换为 json 没有用于 restAPI 的密钥

问题描述

Golang 为 API 设计响应结构

package main

import (
    "encoding/json"
    "fmt"
)

type Optional map[string]interface{}

type Problem struct {
    Name               string
    Description        string
}

type ProblemResponse struct {
    Name               string `json:"name"`
    Description        string `json:"description"`
    Optional
}

func (problem *Problem) ToRes() *ProblemResponse {
    return &ProblemResponse{
        Name: problem.Name,
        Description: problem.Description,
    }
}

func main() {
    problem := Problem{"StackOverflow", "Asking Question"}
    problemRes := problem.ToRes()
    problemRes.Optional = make(map[string]interface{})
    problemRes.Optional["url"] = "https://stackoverflow.com"

    Response(*problemRes)
}

func Response(obj interface{}) {
    data, _ := json.Marshal(obj)
    fmt.Println(string(data))
}

上面的代码将打印

{
  "name": "StackOverflow",
  "description": "Asking Question",
  "Optional": {
    "url": "https://stackoverflow.com"
  }
}

但我想要的是这个

{
  "name": "StackOverflow",
  "description": "Asking Question",
  "url": "https://stackoverflow.com"
}

我希望在主函数中我可以将一些信息附加到 json 响应中。此设计的任何解决方案,它都希望我们不更改响应函数。预先感谢 !!

标签: jsongostruct

解决方案


您可以在结构上实现json.Marshaler接口ProblemResponse,将所有内容转换为平面地图并编码为 JSON。如果一个类型实现了json.Marshaler接口,json 编码器将运行 MarshalJSON 方法。这是文档:https ://golang.org/pkg/encoding/json/#Marshaler

例子:

type Optional map[string]interface{}

type Problem struct {
    Name               string
    Description        string
}

type ProblemResponse struct {
    Name               string `json:"name"`
    Description        string `json:"description"`
    Optional
}

func (p *ProblemResponse) MarshalJSON() ([]byte, error) {

    // we create a flat map including problem's field and optional fields
    // we copy optional first to make sure name and description are not being overwritten from the optional map
    var m = make(map[string]interface{}, 2 + len(p.Optional))
    for k, v := range p.Optional {
        m[k] = v 
    } 
    m["name"] = p.Name
    m["description"] = p.Description 

    return json.Marshal(m)
}

如果你不关心修改Optional,你可以通过这样做来优化in place

func (p *ProblemResponse) MarshalJSON() ([]byte, error) {
    p.Optional["name"] = p.Name
    p.Optional["description"] = p.Description 

    return json.Marshal(p.Optional)
}

如果您有多个需要flattening在 MarshalJSON 上实现这种行为的结构,则可以编写代码生成器。

或者,您可以使用反射并执行类似的操作(您应该通过进行更多检查并使用 json 标记来完成此方法),我不推荐该解决方案,因为您会失去类型安全性:

func Flatten(s interface{}) map[string]interface{} {
        v := reflect.ValueOf(s)
        if v.Kind() == reflect.Ptr {
                v = v.Elem()
        }
        if v.Kind() != reflect.Struct {
                panic(fmt.Errorf("expect struct %T given", s))
        }

        t := v.Type()
        nField := t.NumField()
        r := v.FieldByName("Optional").Interface().(Optional)

        for i := 0; i < nField; i++ {
                f := t.Field(i)
                if f.Name != "Optional" {
                        fv := v.Field(i)
                        // here you could read json tags
                        // to get the value in the json tag instead of ToLower
                        r[strings.ToLower(f.Name)] = fv.Interface()
                }
        }

        return r
}

// usage
b, err i:= json.Marshal(Flatten(problemRes))

或者也许只是使用地图?


推荐阅读