[Go] jsun
๊ด๋ จ ํฌ์คํธ
https://blog.naver.com/sssang97/223184628396
๊นํ
https://github.com/myyrakle/jsun
Go์ ๋ชป๋ ๋ถ๋ถ์ ๋๋นตํ๊ธฐ ์ํด ๋ง๋ JSON ๋์ฝ๋ฉ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ค.
์ฉ์ผ๋ก ๋ง๋ ๊ฑด ์๋๊ณ , encoding/json ๊ฐ์ ธ๋ค๊ฐ ํ์ํ ๋ถ๋ถ์ ๊ณ ์น๊ธฐ๋ง ํ๋ค.
๋์์ด ๋ฌ๋ผ์ง๊ฑด ์ด๋ฐ ๋ถ๋ถ์ด๋ค.
์ด๋ ๊ฒ ๊ฐ์ json ํ๊ทธ๋ช
์ ๊ฐ์ง๋ฉด์ ์คํจ ๊ฐ๋ฅ(failable)ํ๋๋ก ์ค์ ํด๋๋ฉด, ๊ฐ์ json ํ๋๊ฐ์ด ๊ทธ๋๊ทธ๋ ๋ค๋ฅธ ํํ๋ก ์๋ ์ปค๋ฒํ ์ ์๋ค.
failable์ ๋จ์ผ ํ๋์๋ ์ฌ์ฉํ ์ ์๋ค.
unmarshal์ด ์คํจํ ํ๋๋ ๊ทธ๋ฅ zero value ๊ทธ๋๋ก ์ค์ ๋๋ค.
๊ทธ์ ๋ํ ๊ฐ๋จํ ํ ์คํธ์ฝ๋๋ค.
package main
import (
"fmt"
json "github.com/myyrakle/jsun"
)
type TradeDetail struct {
ItemID string `json:"item_id"`
}
type TradeHistory struct {
TradeID string `json:"trade_id"`
DetailList []TradeDetail `json:"detail,failable"`
Detail TradeDetail `json:"detail,failable"`
}
func main() {
testcase1 := `{ "trade_id": "1234", "detail": { "item_id": "abcd" }, "foo": "bar" }`
testcase2 := `{ "trade_id": "1234", "detail": [{ "item_id": "abcd" }] }`
var history TradeHistory
if err := json.Unmarshal([]byte(testcase1), &history); err != nil {
fmt.Println("testcase1 failed")
fmt.Println(err)
} else {
fmt.Println("testcase1 passed")
}
fmt.Printf("history %#v\n", history)
var history2 TradeHistory
if err := json.Unmarshal([]byte(testcase2), &history2); err != nil {
fmt.Println("testcase2 failed")
fmt.Println(err)
} else {
fmt.Println("testcase2 passed")
}
fmt.Printf("history2 %#v\n", history2)
}