普通网友 2016-04-03 05:37
浏览 68

Golang Json Unmarshal数值与指数

I have problem when Unmarshal json string into struct that is the numeric value with exponent will alway be 0. Please check code below :

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

And the run is :

{0 Fernando}

Is there any way to make it work? Since the exponent thing is standart JSON. It seems the golang wrong interpret it.

Here the playground : http://play.golang.org/p/8owgjX9y0m

  • 写回答

2条回答 默认 最新

  • dongxixian7803 2016-04-03 05:48
    关注

    Change the Id type from int64 to float32 or float64.

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

    EDIT: This may be a bit of a hack, but you can add a "dummy" Id field of type float64 and write a hook to cast the value to the actual Id type 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

    评论

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目