登录
首页 >  Golang >  Go问答

将 mapinterface{} 中的项序列化为 int 类型的 JSON

来源:stackoverflow

时间:2024-02-23 09:57:23 427浏览 收藏

来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习Golang相关编程知识。下面本篇文章就来带大家聊聊《将 mapinterface{} 中的项序列化为 int 类型的 JSON》,介绍一下,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我想序列化包 gonum.org/v1/gonum/mat 的类型 dense。由于我无法实现外部类型的方法,因此我创建了一个类型

type denseex struct {
    mtx *mat.dense
}

并实现了 marshaljson 方法,如下

func (d denseex) marshaljson() ([]byte, error) {
    js := map[string]interface{}{}
    rows, cols := d.mtx.dims()
    js["cols"] = cols
    js["rows"] = rows
    fltvals := make([]float64, cols*rows)
    for r := 0; r < rows; r++ {
       for c := 0; c < cols; c++ {
            i := r*cols + c
            fltvals[i] = d.mtx.at(r, c)
        }
    }
  js["values"] = fltvals
  return json.marshal(js)
}

这按预期工作。现在我遇到了解组结构的问题。

func (d denseex) unmarshaljson(data []byte) error {
    js := map[string]interface{}{}
    err := json.unmarshal(data, &js)
    if err != nil {
        return err
    }
    intf, ok := js["cols"]
    if !ok {
        return fmt.errorf("tag 'cols' missing in json data")
    }
    var cols, rows int
    cols, ok = intf.(int)
    if !ok {
        return fmt.errorf("tag 'cols' cannot be converted to int")
    }
    ...
    return nil
}

我无法将标签的值转换为其正确的类型。我的测试 json 字符串是

var jsonstrs = []struct {
    str         string
    expected    denseex
    description string
}{
    {
        str: "{\"cols\":3,\"rows\":2,\"values\":[6,1,5,2,4,3]}",
        expected: denseex{
            mtx: nil,
        },
        description: "deserialization of a 2x3 matrice",
    },
}

我的测试代码是

...
for _, d := range jsonstrs {
    var m denseex
    err := m.unmarshaljson([]byte(d.str))
...

我总能得到结果

matex_test.go:26: FAIL: deserialization of a 2x3 matrice: tag 'cols' cannot be converted to int

有什么想法吗?

提前致谢!


解决方案


如果你检查unmarshal的docs。你会发现unmarshal中已知的numbers类型是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

因此,当您尝试解组一个 int 时,您将得到它作为 float 64。应该首先将其断言键入 float64 intf.(float64),然后将其转换为 int

例如:

intf, ok := js["cols"]
    if !ok {
        return fmt.Errorf("tag 'cols' missing in JSON data")
    }
    var cols, rows int

    ucols, ok := intf.(float64)
    if !ok {
        return fmt.Errorf("tag 'cols' cannot be converted to float64")
    } 

    cols = int(ucols)

到这里,我们也就讲完了《将 mapinterface{} 中的项序列化为 int 类型的 JSON》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>