dssqq64884 2017-11-29 13:55
浏览 17
已采纳

有关扩展的JSON命名策略

My Go struct is like this:

type BaseModel struct {
    Id          string    `json:"id"`
    CreatedTime time.Time `json:"createdTime"`
    UpdatedTime time.Time `json:"updatedTime"`
    Deleted     bool      `json:"deleted"`
}

type Category struct {
    BaseModel        
    Parent    string `json:"parent"`
    Name      string `json:"name"`
    IconClass string `json:"iconClass"`
    Mark      string `json:"mark"`
}

I want convert Category to JSON like this:

{
  "id":"",
  "deleted":"",
  ...
  "parent":"",
  "name":""
}

But when I use Go's json to convert it, it gives me this:

{
  "Id":"",
  "Deleted":"",
  ...
  "parent":"",
  "name":"",
  ...
}

What should I do now?

I use under code to convert:

// define
var menus []models.Category
// query from db
q.Filter("deleted__exact", false).All(&menus)
// serialize it
res, _ := json.Marshal(&menus)
s := string(res[:])
beego.Debug(s)

</div>
  • 写回答

1条回答 默认 最新

  • drwf69817 2017-11-29 14:04
    关注

    Please, add your convert code here. The code below works fine.

    type BaseModel struct {
        Id          string    `json:"id"`
        CreatedTime time.Time `json:"createdTime"`
        UpdatedTime time.Time `json:"updatedTime"`
        Deleted     bool      `json:"deleted"`
    }
    
    type Category struct {
        BaseModel
        Parent    string `json:"parent"`
        Name      string `json:"name"`
        IconClass string `json:"iconClass"`
        Mark      string `json:"mark"`
    }
    
    func main() {
        data, err := json.Marshal(Category{})
        if err != nil {
            return
        }
    
        fmt.Println(string(data[:]))
    }
    

    Output:

    {"id":"","createdTime":"0001-01-01T00:00:00Z","updatedTime":"0001-01-01T00:00:00Z","deleted":false,"parent":"","name":"","iconClass":"","mark":""}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?