3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Go(golang)/ginのAPIでnullableなjsonを返す

Last updated at Posted at 2020-02-14

#状況

var n int
println(n)

// 実行結果
0
  • これでどういう問題が発生するかというと構造体でも初期化した時点で勝手に0が入ってしまいnull値を表現できない。
    • するとgincontextを使ってjson化した際にも、もちろんnull値が入らない。
      • jsonでnullが返せない!
package main

import (
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {

		type NotNullJSON struct {
			NotNullIntInit     int `json:"not_null_id_init"`
			NotNullIntNotInit  int `json:"not_null_id_not_init"`
		}

		notNullJSON := new(NotNullJSON)
		notNullJSON.NotNullIntInit = 1

		c.JSON(200, nullableJSON)
	})
	r.Run()
}

// 実行結果(何も代入していないnot_null_id_not_initにも0が入っている)

{"not_null_id_init":1,"not_null_id_not_init":0}

#対処

  • ポインタを指定すればいい
    • ポインタは代入しなければnullが入っている
package main

import (
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {

		type NullableJSON struct {
			NullableIntInit    *int `json:"nullable_id_init"`
			NullableIntNotInit *int `json:"nullable_id_not_init"`
			NotNullIntInit     int  `json:"not_null_id_init"`
			NotNullIntNotInit  int  `json:"not_null_id_not_init"`
		}

		nullableJSON := new(NullableJSON)
		nullableJSON.NotNullIntInit = 1

		tmpInt := 1
		// 代入方法に注意!
		nullableJson.NullableIDInit = &tmpInt
		c.JSON(200, nullableJSON)
	})
	r.Run()
}

// 実行結果(何も代入していないnullable_id_not_initにnullが入っている)

{"nullable_id_init":1,"nullable_id_not_init":null,"not_null_id_init":1,"not_null_id_not_init":0}

##おまけ・その他

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?