如何解码类型从字符串转换为float64的JSON [英] How to decode JSON with type convert from string to float64

查看:112
本文介绍了如何解码类型从字符串转换为float64的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下浮点数对JSON字符串进行解码:

I need to decode a JSON string with the float number like:

{"name":"Galaxy Nexus", "price":"3460.00"}

我使用下面的Golang代码:

I use the Golang code below:

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)
    }
}

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

When I run it, get the result:

json: cannot unmarshal string into Go value of type float64
{Name:Galaxy Nexus Price:0}

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

I want to know how to decode the JSON string with type convert.

推荐答案

答案不那么复杂.只需添加告诉JSON中介程序,它是一个用,string编码的float64字符串(请注意,我只更改了Price定义):

The answer is considerably less complicated. Just add tell the JSON interpeter it's a string encoded float64 with ,string (note that I only changed the Price definition):

package main

import (
    "encoding/json"
    "fmt"
)

type Product struct {
    Name  string
    Price float64 `json:",string"`
}

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)
    }
}

这篇关于如何解码类型从字符串转换为float64的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆