How Can I Handle Ambiguous Boolean Values (0/1, true/false) When Unmarshalling JSON?

Susan Sarandon
Release: 2024-11-26 22:06:15
Original
611 people have browsed it

How Can I Handle Ambiguous Boolean Values (0/1, true/false) When Unmarshalling JSON?

Handling Ambiguous Boolean Values in JSON with Unmarshalling

When mapping the output of a service that inconsistently represents boolean values as 0 and false (or 1 and true), it becomes necessary to adopt a more permissive approach during unmarshalling. While adding ,string to JSON tags may not suffice, there are alternative solutions available.

Implementing a Custom Type

A solution is to define a custom type, such as ConvertibleBoolean, to handle the ambiguous boolean values. This type includes an UnmarshalJSON method that converts the input data into a boolean value based on the specified conventions.

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
}
Copy after login

This custom type ensures that input values like "1" and "0" are interpreted as boolean values, allowing for parsing without errors.

Pointer Method Receiver

It is important to note that in order for the custom UnmarshalJSON method to function correctly, it must be implemented as a pointer method receiver. This is because pointers allow for modifications to the underlying value.

By utilizing this approach, you can effectively unmarshal ambiguous boolean values from JSON data, ensuring that the resulting struct contains the expected values despite the inconsistencies in the input data.

The above is the detailed content of How Can I Handle Ambiguous Boolean Values (0/1, true/false) When Unmarshalling JSON?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template