Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What is going on with this article?
@whisky-shusuky

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

More than 1 year has passed since last update.

状況

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}

おまけ・その他

1
Help us understand the problem. What is going on with this article?
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
whisky-shusuky
一応サーバーサイドエンジニアですが面白そうなことには何でも首を突っ込みます。 Ruby/Rails/golang/gin/Terraform/Unity/GLSL

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
1
Help us understand the problem. What is going on with this article?