JSON Unmarshal

novtopro · 2016-07-22 09:13:03 · 3052 次点击

那为啥不生成 json 时,就生成为 true / false 呢?

#5
更多评论

不建议这么搞吧。真要搞,这里有一个思路

package main

import "fmt"
import "encoding/json"

func main() {
    var strjson = `{"isok":1,"name":"polaris"}`
    var model = struct {
        Name string  `json:"name"`
        IsOk intbool `json:"isok"`
    }{}

    err := json.Unmarshal([]byte(strjson), &model)
    if err != nil {
        fmt.Println(err)
        return
    }

    fmt.Println(model.IsOk, model.Name)
}

type intbool bool

func (this *intbool) UnmarshalJSON(data []byte) error {
    if "1" == string(data) {
        *this = intbool(true)
    } else {
        *this = intbool(false)
    }
    return nil
}
#1

谢谢你的回复。为什么不建议呢?

#2