JSON Unmarshal

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

哈哈哈。使用 UnmarshalJSON 的方式,它的类型也不是 bool,放入 if 中的也得做下类型转换。

#7
更多评论

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

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