json - 从输入流中读取时属性的类型不一样
问题描述
用于测试列出用户的代码。
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?
解决方案
User.RoleID
是一个整数,它将被编码为一个 JSON 数字。并且因为您解组为类型map[string]interface{}
的值(值类型是接口),float64
所以在解组为接口值时选择类型。
为了将 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
。
推荐阅读
- python-3.x - 使用嵌套列表作为值将数据输入到字典(可能来自文件)
- arduino - Arduino Uno 可用内存不足
- angular - Angular - 之后的回调函数
- swift - 将 Swift 字符串从 a 部分拆分到 b 部分?
- matlab - 当我使用 UIGETFILE 函数时,我的 gui 最小化。我怎样才能阻止这样做呢?
- alexa - 该技能是 Alexa 参考或模板示例技能的副本错误
- ocaml - 返回矩形范围内的元组列表
- python - 如何过滤本周的 django 查询集
- c - ESP-IDF:通过 http 服务器配置 wifi 连接
- java - 如何使用类和子类修复 setContentView 和 super.onCreate 方法?