Help us understand the problem. What is going on with this article?

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

状況

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}

おまけ・その他

whisky-shusuky
一応サーバーサイドエンジニアですが面白そうなことには何でも首を突っ込みます。 Ruby/Rails/golang/gin/Terraform/Unity/GLSL
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした