Skip to content

UnmarshalTypeError hook support ??? #5

Open
@skybosi

Description

@skybosi
package main

import (
	"encoding/json"
	"fmt"

	"github.com/titanous/json5"
)

type (
	R2 struct {
		Code     int         `json:"code,string"`
		FloatNum float32     `json:"float_num,string"`
		Code2    int         `json:",string"`
		Msg      string      `json:"msg,omitempty"`
		Data     interface{} `json:",omitempty"`
		Data2    interface{} `json:",omitempty"`
		Id       int         `json:"-"`
		Id2      int         `json:"-,"`
	}
)

func main() {
	r2, _ := json.Marshal(R2{Code: 0, Msg: "", Data: "字符串数据", Data2: nil, Code2: 999, Id: 1000, Id2: 2000})
	fmt.Println(string(r2)) // {"code":"0","Code2":"999","Data":"字符串数据","-":2000}

	rs2 := `{code:"666w", float_num:'11.12', "Code2":"999","Data":"字符串数据","-":2000}`
	rsr := &R2{}
	err := json5.Unmarshal([]byte(rs2), rsr)
	if err == nil {
		fmt.Println(rsr)
	} else {
		fmt.Println(err)
	}
}

result:
{"code":"0","float_num":"0","Code2":"999","Data":"字符串数据","-":2000}
json: cannot unmarshal number 666w into Go value of type int

can we get ,parse int failed, use default value ?
number:
int, int32, int64, uint32, uint64 ... -> 0
float32 float64 -> 0.0

maybe , you can provide a hook, while ParseInt , ParseFloat

		n, err := strconv.ParseInt(h, 16, 64)
		if err != nil {
                         // add hook here, if not add hook, use default  error handler
			return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0), int64(d.off)}
		}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions