如何从JSON解除0和false两者作为bool [英] How to unmarshall both 0 and false as bool from JSON

查看:247
本文介绍了如何从JSON解除0和false两者作为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在映射一个服务的输出,可以说,它的布尔类型自由地交换0和假(以及1和真)。有没有办法使用内置的encoding / json unmarshal函数更宽松的解析器?我试过向json标签添加字符串,无济于事。

Currently am mapping the output of a service that, lets say, liberally interchanges 0 and false (and 1 and true) for its boolean types. Is there a way to use a more permissive parser for the built in encoding/json unmarshal function? I've tried adding ,string to the json tags to no avail.

一个我想要的例子:

An example of what I'd want:

type MyType struct {
    AsBoolean bool `json:"field1"`
    AlsoBoolean bool `json:"field2"`
}

然后,给定输入json:

then, given input json:

{
    "field1" : true,
    "field2" : 1
}

be:

the resulting struct would be:

obj := MyType{}
json_err := json.Unmarshal([]byte(input_json), &obj)
fmt.Printf("%v\n", obj.AsBoolean) //"true"
fmt.Printf("%v\n", obj.AlsoBoolean) //"true"


推荐答案

类型,以及我在哪里使用正常的布尔,换成这个:

Ended up using a special "boolean" type, and where I was using a normal bool, swapped for this:

type ConvertibleBoolean bool

func (bit ConvertibleBoolean) UnmarshalJSON(data []byte) error {
    asString := string(data)
    if asString == "1" || asString == "true" {
        bit = true
    } else if asString == "0" || asString == "false" {
        bit = false
    } else {
        return errors.New(fmt.Sprintf("Boolean unmarshal error: invalid input %s", asString))
    }
    return nil
}

这篇关于如何从JSON解除0和false两者作为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆