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
版权声明:本文标题:go - How to handle jsonapi returning empty struct for struct with false value in golang - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736609967a1945420.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论