Web/GoLang

[Golang] Json 데이터를 파싱할때 자동으로 형변환까지 한번에 하는 방법

벨포트조던 2021. 7. 28.
반응형

Golang의 기본 패키지 Json는 여러 기능을 제공한다.

이번 포스트에서는 의외로 사람들이 모르는 꿀팁을 공유하려고 한다.

Json

{"key1":1, "key2":"2", "key3":[1,2,3]}

 

예를들어서 이렇게 생긴 Json 구조가 있다고 할때 key1 은 integer이나 key2 는 string 형태이다.

 

type AutoGenerated struct {
	Key1 int    `json:"key1"`
	Key2 string `json:"key2"`
	Key3 []int  `json:"key3"`
}

type AutoGenerated struct { Key1 int `json:"key1"` Key2 string `json:"key2"` Key3 []int `json:"key3"` }

일반적으로 위 key2 를 string 이 아닌 integer 형태로 가져온다면 위와같이 구조체를 만들고 이후에 Integer 로 변환을 하던가 등등 다양한 방법으로 할 것이다.

하지만 이렇게 사용하지 않고 파싱할때부터 아예 형 변환이 가능하다!

type AutoGenerated struct {
	Key1 int    `json:"key1"`
	Key2 int    `json:"key2,string"`
	Key3 []int  `json:"key3"`
}

 

달라진점은 Key2  int 형이라는 것이고 json annotation 뒤에 ,string 이 붙었다.

그렇다 딱 눈에 봐도 바로 들어올 것이다.

Key2 는 본인이 원하는 int 형으로 선언해두고 annotation 에는 ,string(원본 자료형)을 붙여서 변환하라는 의미이다!

테스트

Full example

package main

import (
	"fmt"
	"encoding/json"
)

type Test struct {
	Key1 int    `json:"key1"`
	Key2 int    `json:"key2,string"`
	Key3 []int  `json:"key3"`
}


func main() {

	testJson := []byte(`{"key1":1, "key2":"2", "key3":[1,2,3]}`)
	testStruct := &Test{};
	json.Unmarshal(testJson, testStruct);
	fmt.Println(testStruct)
}

완료!

 

 

https://velog.io/@sweetchip/Golang-Json-%ED%8C%8C%EC%8B%B1%ED%95%A0%EB%95%8C-%EC%9E%90%EB%8F%99-%ED%98%95%EB%B3%80%ED%99%98%EA%B9%8C%EC%A7%80-%ED%95%9C%EB%B2%88%EC%97%90-%ED%95%98%EA%B8%B0

반응형

댓글