programing

JSON 골랑 부울 생략

elecom 2023. 4. 3. 21:15
반응형

JSON 골랑 부울 생략

API용 골랑 라이브러리 작성에 문제가 있습니다.부란의 json 측면이 문제를 일으키고 있습니다.

API 콜의 경우 부울의 디폴트값이 true라고 합니다.

내가 하면

SomeValue bool `json:some_value,omitempty`

라이브러리를 통해 값을 설정하지 않으면 값이 true로 설정됩니다.라이브러리에서 값을 false로 설정하면 issempty는 false 값은 빈 값이기 때문에 api 호출을 통해 값이 true로 유지됩니다.

빈칸을 빼고 이렇게 하자.

SomeValue bool `json:some_value`

반대의 문제가 있습니다.값을 false로 설정할 수 있지만 값을 설정하지 않으면 true로 예상해도 false가 됩니다.

편집: 값을 false로 설정할 수 있을 뿐만 아니라 값을 true로 설정할 필요가 없는 동작을 유지하려면 어떻게 해야 합니까?

포인터 사용

package main

import (
    "encoding/json"
    "fmt"
)

type SomeStruct struct {
    SomeValue *bool `json:"some_value,omitempty"`
}

func main() {
    t := new(bool)
    f := new(bool)

    *t = true
    *f = false

    s1, _ := json.Marshal(SomeStruct{nil})
    s2, _ := json.Marshal(SomeStruct{t})
    s3, _ := json.Marshal(SomeStruct{f})

    fmt.Println(string(s1))
    fmt.Println(string(s2))
    fmt.Println(string(s3))
}

출력:

{}
{"some_value":true}
{"some_value":false}

gaav의 답변의 계속으로.대신 언마샬링에도 같은 문제가 있었습니다.값이 제공되었는지 여부를 확인하려면 포인터가 0인지 확인하기만 하면 됩니다.

type SomeStruct struct {
    SomeValue *bool `json:"some_value,omitempty"`
}

func HandleApiRequest(w http.ResponseWriter, r *http.Request) {
  body := new(SomeStruct)

  reqBody, err := ioutil.ReadAll(r.Body)
  if err != nil {
         panic(err)
  }

  err := json.Unmarshal(reqBody, body)
  if err != nil {
    panic(err)
  }

  if body.SomeValue != nil {
    // SomeValue is provided in the body and is a valid boolean
    // Do something with *body.SomeValue
    log.Println("Some Value is:", *body.SomeValue)
  } else {
    // SomeValue was NOT sent in json body
    // Will panic with a fault if you tried accessing *body.SomeValue
  }
}

언급URL : https://stackoverflow.com/questions/37756236/json-golang-boolean-omitempty

반응형