【问题标题】:Golang Json Unmarshal numeric with exponentGolang Json Unmarshal 带指数的数字
【发布时间】:2019-09-04 18:10:48
【问题描述】:

当将 json 字符串解组到结构中时,我遇到问题,即指数的数值始终为 0。 请检查以下代码:

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

type Person struct {
    Id   uint64  `json:"id"`
    Name string `json:"name"`
}

func main() {

    //Create the Json string
    var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`)

    //Marshal the json to a proper struct
    var f Person
    json.Unmarshal(b, &f)

    //print the person
    fmt.Println(f)

    //unmarshal the struct to json
    result, _ := json.Marshal(f)

    //print the json
    os.Stdout.Write(result)
}

运行是:

{0 Fernando}

有什么方法可以让它工作吗?由于指数是标准的 JSON。看来golang的解释错了。

这里是游乐场:http://play.golang.org/p/8owgjX9y0m

【问题讨论】:

  • 我猜这里的问题是 Go unmarshaller 不接受用指数表示法指定的整数——解组为 float64 然后转换为 uint64 是否可行?
  • 我相信这是由类型引起的问题,我感觉 OP 希望该字段为 uint64。所以正确的做法是将JSON字段类型改为float64,然后在你想使用的时候进行类型转换为uint64。
  • 是的,看来我们需要一个浮点数。但是有可能使它成为int64吗?还是我需要手动转换?

标签: json go


【解决方案1】:

Id 类型从int64 更改为float32float64

http://play.golang.org/p/-zidTD_q8y

编辑:这可能有点小技巧,但您可以添加一个float64 类型的“虚拟”Id 字段并编写一个挂钩将值转换为实际的@ 987654329@ 输入int64

type Person struct {
    Id    float64          `json:"id"`
    _Id   int64             
    Name  string           `json:"name"`
}

var f Person
var b = []byte(`{"id": 1.2e+8, "Name": "Fernando"}`)
_ = json.Unmarshal(b, &f)

if reflect.TypeOf(f._Id) == reflect.TypeOf((int64)(0)) {
    fmt.Println(f.Id)
    f._Id = int64(f.Id)
}

http://play.golang.org/p/32HHLxnFlX

【讨论】:

  • 但我需要 int 而不是浮点数。
  • 为什么要使用反射来检查已知类型? f._Id 不可能是 int64 以外的任何东西。
【解决方案2】:

只需将id字段的类型改为float64即可。

package main
import (
    "encoding/json"
    "fmt"
    "os"
)

type Person struct {
    Id   float64  `json:"id"`
    Name string   `json:"name"`
}

func main() {

    //Create the Json string
    var b = []byte(`{"id": 1.2E+8, "Name": "Fernando"}`)

    //Marshal the json to a proper struct
    var f Person
    json.Unmarshal(b, &f)

    //print the person
    fmt.Println(f)

    //unmarshal the struct to json
    result, _ := json.Marshal(f)

    //print the json
    os.Stdout.Write(result)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2015-03-15
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多