json - 从输入流中读取时属性的类型不一样

标签 json go struct numbers

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

    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{} 类型的值(值类型为接口(interface)),float64解码为接口(interface)值时选择类型。
引自 json.Unmarshal() :

To unmarshal JSON into an interface value, Unmarshal stores one of these in the interface value:

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对象,解码为 User 类型的值.

关于json - 从输入流中读取时属性的类型不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59152703/

相关文章:

c - C 中的内存分段

c - 是否可以在 C 的结构中创建 'empty' 成员?

javascript - 如何从json中删除多余的 ','

go - 读者多次阅读

在尝试发送之前进行非阻塞 channel 发送,测试是否失败?

go - 对于实现函数式语言的虚拟机,有哪些明显的优化?

c# - Newtonsoft.Json 使用 php 7.0 json_encode 数组字符串反序列化问题

javascript - 如何在 Angular 中创建非链接变量?

javascript - 编写一个函数对对象数组进行排序(通过使用另一个对象来指定排序路径和顺序)

c - 在c中将结构体添加到链表中