0
0

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のjson.Marshalで空のオブジェクトが返ってくる時の解決法

Posted at

空のオブジェクトが入るとき

func A() string {
	type ResponseData struct {
        //先頭が小文字なので公開されてない
		name  string
		value int64
	}
	var rd []ResponseData
    rd = append(rd,ResponseData{
        name:"aaa",
        value:1
   })
	resRaw, _ := json.Marshal(rd)
	resultJSON := string(resRaw)
	return resultJSON
}

ResponseDataのフィールドが公開されていません。
これをすると、resultJSONに[{}]←こんなんが入ります。

OKなやつ

func A() string {
	type ResponseData struct {
        //先頭が大文字なので公開されている
		Name  string
		Value int64
	}
	var rd []ResponseData
    rd = append(rd,ResponseData{
        Name:"aaa",
        Value:1
   })
	resRaw, _ := json.Marshal(rd)
	resultJSON := string(resRaw)
	return resultJSON
}

こうするとResponseDataのフィールドがエクスポートされているので、結果的にresultJSONにちゃんと値が入ります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?