小编yan*_*non的帖子

如何在Golang中解码类型从字符串转换为float64的JSON?

我需要解码一个带有浮点数的JSON字符串,如:

{"name":"Galaxy Nexus", "price":"3460.00"}
Run Code Online (Sandbox Code Playgroud)

我使用下面的Golang代码:

package main

import (
    "encoding/json"
    "fmt"
)

type Product struct {
    Name  string
    Price float64
}

func main() {
    s := `{"name":"Galaxy Nexus", "price":"3460.00"}`
    var pro Product
    err := json.Unmarshal([]byte(s), &pro)
    if err == nil {
        fmt.Printf("%+v\n", pro)
    } else {
        fmt.Println(err)
        fmt.Printf("%+v\n", pro)
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行它时,得到结果:

json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}
Run Code Online (Sandbox Code Playgroud)

我想知道如何使用convert类型解码JSON字符串.

json go

73
推荐指数
3
解决办法
6万
查看次数

标签 统计

go ×1

json ×1