首页 > 解决方案 > 从输入流中读取时属性的类型不一样

问题描述

用于测试列出用户的代码。

    req := httptest.NewRequest("GET", "/v1/users", nil)
    resp := httptest.NewRecorder()

    u.app.ServeHTTP(resp, req)

    if resp.Code != http.StatusOK {
        t.Fatalf("getting users: expected status code %v, got %v", http.StatusOK, resp.Code)
    }

    var list []map[string]interface{}
    if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
        t.Fatalf("decoding users: %s", err)
    }

    want := []map[string]interface{}{
        {
            "id":           "a2b0639f-2cc6-44b8-b97b-15d69dbb511e",
            "name":         "dcc",
            "role_id":      float64(101),
            "date_created": "2019-01-01T00:00:01Z",
            "date_updated": "2019-01-01T00:00:01Z",
        },
    }

role_id 是模型中的 int 类型。

type User struct {
    ID          string    `db:"user_id" json:"id"`
    UserName    string    `db:"user_name" json:"user_name"`
    RoleID      int       `db:"role_id" json:"role_id"`
    DateCreated time.Time `db:"date_created" json:"date_created"`
    DateUpdated time.Time `db:"date_updated" json:"date_updated"`
}

为什么输入到流中时改为float64?

标签: jsongostructnumbers

解决方案


User.RoleID是一个整数,它将被编码为一个 JSON 数字。并且因为您解组为类型map[string]interface{}的值(值类型是接口),float64所以在解组为接口值时选择类型。

引自json.Unmarshal()

为了将 JSON 解组为接口值,Unmarshal 将其中一项存储在接口值中:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

如果您知道响应包含一个User对象,请解组为 type 的值User


推荐阅读