2015-05-10 74 views
3

进口结构设置标签我使用gormØORM)来检索从我的数据库将在JSON编码数据。 Gorm为主键和时间跟踪提供了一个默认结构,其中的DeletedAt属性不应该用JSON编码。在围棋

我写了一个小例子,即不会输出密码,但DeletedAt属性仍然可见。

package main 

import (
    "encoding/json" 
    "fmt" 
    "os" 

    "github.com/jinzhu/gorm" 
    _ "github.com/lib/pq" 
    _ "github.com/mattn/go-sqlite3" 
) 

// Struct from the gorm package: 
// 
// type Model struct { 
//  ID  uint `gorm:"primary_key"` 
//  CreatedAt time.Time 
//  UpdatedAt time.Time 
//  DeletedAt *time.Time 
// } 

// Defines the database model for gorn 
type User struct { 
    gorm.Model 
    Username string `json:"username" sql:"size:32; not null; unique"` 
    Password string `json:"password" sql:"not null"` 
    Locale string `json:"locale" sql:"not null"` 
} 

// Public JSON version of database model 
type PublicUser struct { 
    *User 
    DeletedAt bool `json:"deletedAt,omitempty"` 
    Password bool `json:"password,omitempty"` 
} 

func main() { 
    db, err := gorm.Open("sqlite3", "storage.db") 

    if err != nil { 
     fmt.Println(err) 
    } 

    u := &User{} 
    db.Where("id = ?", 3).Find(&u) 

    json.NewEncoder(os.Stdout).Encode(PublicUser{ 
     User: u, 
    }) 
} 

这是可能输出我得到的,如果我跑我的脚本:

{ 
    "ID":3, 
    "CreatedAt":"2015-05-13T14:54:23.5577227Z", 
    "UpdatedAt":"2015-05-13T14:54:23.5577227Z", 
    "DeletedAt":null, 
    "username":"dan", 
    "locale":"en_US" 
} 

我修改阿尔弗雷德·罗西的example模仿行为,我得到了相同的结果。

+0

案件事宜。您需要将DeletedAt bool设置为序​​列化为'json:“DeletedAt,omitempty”。 Captial D在结果中剔除“DeletedAt”。 –

回答

2

你可以只影现场与布尔设置为false,并与omitempty

标记它例如

type User struct { 
    Username string `json:"username"` 
    DeletedAt int `json:"deleted_at"` 
} 

type PublicUser struct { 
    *User 
    DeletedAt bool `json:"deleted_at,omitempty"` 
} 

随时用它here玩。另请参阅AttilaOláh的this blog post

+0

感谢您的提示。 – user3147268

+0

如果你只有一个父结构,使用阴影方法效果很好,但在我的情况下,我有一个不能被阴影化的祖父母结构(gorm.Model)。 [看这里](https://play.golang.org/p/WQxbLSUX4R)。 – user3147268

+0

Shadowing works fine,the problem is that the Json key is set to deletedAt and you are shadowing deleted_at –