Home >Backend Development >Golang >How to Handle Multiple JSON Boolean Representations When Unmarshalling in Go?

How to Handle Multiple JSON Boolean Representations When Unmarshalling in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 00:19:15313browse

How to Handle Multiple JSON Boolean Representations When Unmarshalling in Go?

Unmarshalling JSON Booleans with Multiple Representations

When unmarshalling JSON into a boolean type, the built-in encoding/json unmarshal function expects values such as "true" and "false". However, certain services may interchange "0" and "false" (as well as "1" and "true") for boolean types.

To accommodate this flexibility, it's possible to create a custom unmarshaling function that converts string values such as "0", "1", "false", and "true" to the desired boolean representation.

Here's an example of a custom type ConvertibleBoolean that can be used to unmarshal boolean values with multiple representations:

import (
    "encoding/json"
    "errors"
)

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
}

With this custom type, you can define a struct with fields of type ConvertibleBoolean and unmarshal JSON data containing "0" and "false" as booleans:

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

Upon unmarshaling input JSON with convertible boolean values, the ConvertibleBoolean fields in the struct will be correctly populated:

input_json := `{
    "field1" : true,
    "field2" : 1
}`

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

By using a custom unmarshaling function like ConvertibleBoolean, it's possible to handle boolean values with multiple representations in JSON data when unmarshalling into Go structs.

The above is the detailed content of How to Handle Multiple JSON Boolean Representations When Unmarshalling in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn