json-iterator / go

A high-performance 100% compatible drop-in replacement of "encoding/json"
http://jsoniter.com/migrate-from-go-std.html
MIT License
13.43k stars 1.03k forks source link

Automatically omit decimals when using MarshalToString #522

Closed CHN-STUDENT closed 3 years ago

CHN-STUDENT commented 3 years ago

eg

package main

import (
    "fmt"
    "github.com/json-iterator/go"
)

type ClientInfo struct {
    CPU float64 `json:"cpu"`
}

func NewDefaultClientInfo() ClientInfo {
    return ClientInfo {
        CPU: 0.0,
    }
}

func main() {
    var clientInfo = NewDefaultClientInfo()
    clientInfo.CPU = 12.0
    data, _ := jsoniter.MarshalToString(&clientInfo)
    fmt.Println(data)
}

Expected value: { "CPU": 12.0 }

Actual value: { "CPU": 12 }

I do not hope automatically omit decimals my float64 value, so could you tell me how to solve it? Thanks!

bytegaurav commented 3 years ago

It is a default behaviour even in encoding/json library since it treats float64 and int as JSON numbers. Read here https://golang.org/pkg/encoding/json/#Unmarshal

To keep decimal intact, you can define your own type for float and implement MarshalJSON method on that type.

CHN-STUDENT commented 3 years ago

@bytegaurav ok. thanks! i define my own type json date to solve it. Glad to get your help!