admin管理员组

文章数量:1123931

It looks like jsonapi.Marshal returns an empty json object for a golang struct with a value that is false. I understand that a struct of zero values is considered zero, but as a caller of this API, am I supposed to just know that empty json object means false?

Here is an example. "Active" is either {"value": true} or {} but never {"value": false}.

package main

import (
    "fmt"
    "log"

    "github/DataDog/jsonapi"
    "github/golang/protobuf/ptypes/wrappers"
)

type MyResource struct {
    ID     string              `jsonapi:"primary,my-resource"`
    Active *wrappers.BoolValue `jsonapi:"attribute"`
}

func main() {
    // Create an instance of MyResource with Active set to true
    resource := &MyResource{
        ID:     "1",
        Active: &wrappers.BoolValue{Value: true},
    }

    // Marshal the struct into JSON:API format
    data, err := jsonapi.Marshal(resource)
    if err != nil {
        log.Fatalf("Error marshalling resource: %v", err)
    }

    // Print the JSON result
    fmt.Println(string(data))

    // Create an instance of MyResource with Active set to false
    resource2 := &MyResource{
        ID:     "1",
        Active: &wrappers.BoolValue{Value: false},
    }

    // Marshal the struct into JSON:API format
    data2, err := jsonapi.Marshal(resource2)
    if err != nil {
        log.Fatalf("Error marshalling resource: %v", err)
    }

    // Print the JSON result
    fmt.Println(string(data2))
}

// prints the following:
// {"data":{"id":"1","type":"my-resource","attributes":{"Active":{"value":true}}}}
// {"data":{"id":"1","type":"my-resource","attributes":{"Active":{}}}}

Thanks!

本文标签: goHow to handle jsonapi returning empty struct for struct with false value in golangStack Overflow